我有一份这样的文件..

"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用于判断数组中的元素是否与指定的匹配表达式匹配.

测试数据

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

Mongodb相关问答推荐

在MongoDB中,如何使用$in来匹配存储在数组变量中的值

Mongo聚合项目数组交集

如何在MongoDB中查找和过滤嵌套数组

如何在Mongodb Mongoose Nodejs中提取不等于一组值的字段

spring-data-mongodb 上的 TopN 聚合

Mongodb Timeseries / Golang - ['timestamp' 必须存在并包含有效的 BSON UTC 日期时间值]

我可以在 MongoDB 中将字段值设置为对象键吗?

Golang:如何判断 collection.Find 是否没有找到任何文件?

Mongodb聚合查找异常值

有没有一种方法可以找到一个文档并通过 Go 更改 mongodb 中的 id/value 来克隆它

Java MongoDB/BSON 类混淆

Node.js 和 Passport 对象没有方法 validPassword

使用 nodejs/mongoose 部分更新子文档

为 php 5.6 (XAMPP) 添加 mongodb 扩展

`fields cannot be identical'和''` mongoimport错误

使用 Spring Security + Spring 数据 + MongoDB 进行身份验证

我在更新中对 $set 和 $inc 做错了什么

错误:需要数据和盐参数

带有 either or查询的mongoose findOne

使用 Mongoose ORM 的杀手锏是什么?