2

在 mongo 控制台中,我有:

> 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 编写第二个和第三个查询?

4

2 回答 2

5

这是迄今为止我找到的最佳解决方案:

...

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) );

...
于 2013-04-08T08:56:30.857 回答
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);
于 2014-11-22T00:14:13.373 回答