假设我有一个包含以下文档的集合:
{ "_id": 1, name: "Apple" }
{ "_id": 2, name: "Banana", "is_reported": null }
{ "_id": 3, name: "Cherry", "is_reported": false }
{ "_id": 4, name: "Kiwi", "is_reported": true }
是否有更简单的查询来选择“is_reported”处于虚假状态的所有文档;也就是说,要么不存在,要么为空,要么为假?也就是说,查询选择 Apple、Banana 和 Cherry,但不选择 Kiwi?
According to the MongoDB FAQ , { "is_reported": null }
将选择 "is_reported"为 null 或不存在的文档,但它仍然不会选择 "is_reported"为 false 的文档。
现在我有以下查询,它工作正常,但它看起来不是很优雅。如果我需要选择多个字段,它会很快变得困惑。是否有更好的查询可以达到相同的最终结果?
db.fruits.find({ $or: [ { "is_reported": null }, { "is_reported": false } ] })
最佳答案
您可以使用 $in
来执行此操作:
db.fruits.find({is_reported: {$in: [null, false]}})
返回:
{
"_id": 1,
"name": "Apple"
}
{
"_id": 2,
"name": "Banana",
"is_reported": null
}
{
"_id": 3,
"name": "Cherry",
"is_reported": false
}
如果除了 true
之外没有任何值要排除,您也可以在逻辑上翻转并使用 $ne
:
db.fruits.find({is_reported: {$ne: true}})
https://stackoverflow.com/questions/22290538/
相关文章:
mongodb - 在现有的 mongodb 中恢复单个集合
arrays - Mongoose save() 不更新数据库文档中数组中的值
node.js - CouchDB、MongoDB 和 Redis 中的哪个数据库适合从 Node.
python - 使用 MongoDB ( Python ) 将新属性插入文档
spring - Spring Data MongoDB 和 Hibernate OGM for M
java - java - 如何使用java api查询 “like”的mongodb?