本文介绍了MongoDB Spring 数据 Criteria.all的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 }, {键":三",值":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 }, {键":三",值":3 } ] }>db.test.find({_id:ObjectId("515afcfedba6a529520becfa"), 数组:{$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 ?

解决方案

这是我目前找到的最佳解决方案:

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

In mongo console I have:

> 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 } ] }

How do I write the second and third query using:org.springframework.data.mongodb.core.query.Criteria ?

解决方案

This is the best solution I found so far:

...

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

...

这篇关于MongoDB Spring 数据 Criteria.all的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:55