mongodb - 查询 MongoDB 中的数组数组

说,我有这样的文件..

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

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

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

以下工作虽然有效,但无济于事。

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

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

最佳答案

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

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

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

https://stackoverflow.com/questions/12629692/

相关文章:

mongodb - mongorestore 失败 : no reachable servers

mongodb - 如何使用多个键有效地执行 "distinct"?

mongodb - 如何使用 mongodb 更新包含在父对象数组中的对象的属性?

mongodb - 在 MongoDB 中存储 null 与根本不存储 key

MongoDB - 安装错误 - mongodb 设置向导过早结束

c# - 如何使用官方 c# 驱动程序在 MongoDB 中使用 Update.Set 更新多个字段

node.js - Redis 缓存和 Mongo 的持久性架构

mongodb - EventStore 与 MongoDb

javascript - Meteor 文档中的消息计数示例如何工作?

mongodb - insert()、insertOne() 和 insertMany() 方法有什