查询MongoDB中的数组数组

raj*_*net 42 multidimensional-array mongodb

说,我有这样的文件..

"ID" : "fruit1",
"Keys" : [["apple", "carrot", "banana"]]
Run Code Online (Sandbox Code Playgroud)

如何查询Keys ="carrot".以下语法均不起作用.

db.myColl.results.find({ "Keys" : "carrot" });
db.myColl.results.find({ "Keys" : [["carrot"]] });
Run Code Online (Sandbox Code Playgroud)

以下工作,但没有帮助.

db.myColl.results.find({ "Keys" : [["apple", "carrot", "banana]]});
Run Code Online (Sandbox Code Playgroud)

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

Ram*_*Vel 127

有趣的问题,这将成功

 db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})
Run Code Online (Sandbox Code Playgroud)

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

测试数据    

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" ] ] }
Run Code Online (Sandbox Code Playgroud)

  • 你得到100分.很棒的答案:) (4认同)
  • 或者考虑使用数组的子文档数组。db.multiArrTest.insert({"ID" : "fruit1","Keys" : [{"array" : ["苹果", "胡萝卜", "香蕉"]}, {"array": ["a", "b", "c"]}]}) db.multiArrTest.find({'Keys.array': "胡萝卜"}) (2认同)