2013-04-02 139 views
1

在蒙戈控制檯我:MongoDB的春天數據Criteria.all

> db.test.find({}) 
{ "_id" : ObjectId("515afcfedba6a529520becfa"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 } ] } 
{ "_id" : ObjectId("515b0e48dba6a529520becfd"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 }, {"key" :"three", "value" : 3 } ] } 


> db.test.find({array: {$all:[{key:'one', value:1}, {key:'two',value:2}]}}); 
{ "_id" : ObjectId("515afcfedba6a529520becfa"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 } ] } 
{ "_id" : ObjectId("515b0e48dba6a529520becfd"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 }, {"key" :"three", "value" : 3 } ] } 

> db.test.find({_id:ObjectId("515afcfedba6a529520becfa"), array: {$all:[{key:'one', value:1}, {key:'two',value:2}]}}); 
{ "_id" : ObjectId("515afcfedba6a529520becfa"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 } ] } 

我怎樣寫使用第二和第三個查詢: org.springframework.data.mongodb.core.query.Criteria?

回答

3

這是我迄今發現的最好的解決辦法:

... 

DBObject obj = new BasicDBObject(); 
obj.put("key", 1); 
obj.put("value", "one"); 
DBObject obje1 = new BasicDBObject(); 
obje1.put("$elemMatch", obj); 

obj = new BasicDBObject(); 
obj.put("key", 2); 
obj.put("value", "two"); 
DBObject obje2 = new BasicDBObject(); 
obje2.put("$elemMatch", obj); 

Query qry = new Query(where("array").all(obje1, obje2)); 

... 
0

下面是我想將工作的一個選項:

Criteria criteria = new Criteria("array"); 
criteria.all(Criteria.where("key").is(1).and("value").is("one"),Criteria.where("key").is(2).and("value").is("two")); 
Query query = new Query(criteria);