2014-06-20 101 views
0

我有以下对象:查询文件 - 春天数据的MongoDB

{ 
    "id" : "sampleId"; 
    foos : [{ 
     "prop1":"value1", 
     "prop2":"value2" 
     }, 
     { 
     "prop1":"value3", 
     "prop2":"value4" 
     } 
]} 

我怎样才能得到foos,其中prop2value4?我正在使用Spring数据mongodb。

回答

0

此代码将返回一个ID为sampleId的SampleBean,只有收集foos中的匹配项。

// Match one document with sampleId 
Query q1 = new Query(where("id").is("sampleId")); 

// match only foos with prop2 value value2 
Query q2 = query(where("foos").elemMatch(where("prop2").is("value2)) 

BasicQuery query = new BasicQuery(q1.getQueryObject(), q2.getQueryObject()); 
SampleBean result = mongoTemplate.findOne(query, SampleBean.class) 
0

如果您使用弹簧数据mongodb存储库,它可以使您的生活变得轻松。您将需要一个域类。例如

public class Foo { 
    String prop1; 
    String prop2; 
} 

public class MyClass { 
    String id; 
    List<Foo> foos; 
} 

public interface MyClassRepository extends MongoRepository<MyClass, String> { 
    List<MyClass> findByFoosProp2(String prop2ValueToLookFor); 
    // assuming you can find multiple matches 
} 

然后简单地从你的代码中调用这个方法

public clsss SomeBusinessClass { 
    @Autowired 
    private MyClassRepository repository; 

    public void mySomeBusinessMethod() { 
     List<MyClass> myObjects = repository.findByFoosProp2("value4"); 
    } 
}