查询 MongoDB 中的数组数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12629692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:51:45  来源:igfitidea点击:

Querying an array of arrays in MongoDB

mongodbmultidimensional-array

提问by rajibdotnet

Say, I have a document like this..

说,我有一个这样的文件..

"ID" : "fruit1",
"Keys" : [["apple", "carrot", "banana"]]

How do I query for Keys = "carrot". None of the following syntax works.

如何查询 Keys = "carrot"。以下语法均无效。

db.myColl.results.find({ "Keys" : "carrot" });
db.myColl.results.find({ "Keys" : [["carrot"]] });

Following works though, but not helpful.

虽然以下有效,但没有帮助。

db.myColl.results.find({ "Keys" : [["apple", "carrot", "banana]]});

Any pointer to this query will be helpful. Thanks.

任何指向此查询的指针都会有所帮助。谢谢。

回答by RameshVel

Interesting question, This will do the trick

有趣的问题,这会解决问题

 db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})

$elemMatchused to check if an element in an array matches the specified match expression. so nested $elemMatchwill go deeper into nested arrays

$elemMatch用于检查数组中的元素是否与指定的匹配表达式匹配。所以嵌套$elemMatch将深入到嵌套数组中

Test data ? ?

测试数据 ??

db.multiArr.insert({"ID" : "fruit1","Keys" : [["apple", "carrot", "banana"]]})
db.multiArr.insert({"ID" : "fruit2","Keys" : [["apple", "orange", "banana"]]})


db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})
{ "_id" : ObjectId("506555212aeb79b5f7374cbf"), "ID" : "fruit1", "Keys" : [ [ "apple", "carrot", "banana" ] ] }

db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['banana']}}}})

{ "_id" : ObjectId("506555212aeb79b5f7374cbf"), "ID" : "fruit1", "Keys" : [ [ "apple", "carrot", "banana" ] ] }
{ "_id" : ObjectId("5065587e2aeb79b5f7374cc0"), "ID" : "fruit2", "Keys" : [ [ "apple", "orange", "banana" ] ] }

回答by KARTHIKEYAN.A

if you want to find array of first position data, use 0 as reference index to get data in nested array.

如果要查找第一个位置数据的数组,请使用 0 作为参考索引以获取嵌套数组中的数据。

db.getCollection('routes').find({"routeId" : 12,'routes._id':ObjectId("598da27a713f3e6acd72287f"),'routes.0.stops.0.orders.0._id':ObjectId("598da27a713f3e6acd722887")})