选择一个字段不存在,为null或为false的MongoDB文档?

时间:2014-03-10 01:16:14

标签: mongodb mongodb-query database

假设我有一个包含以下文档的集合:

{ "_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 } ] })

1 个答案:

答案 0 :(得分:71)

您可以使用$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
}

如果除了$ne之外没有任何值可以排除,您还可以逻辑翻转并使用true

db.fruits.find({is_reported: {$ne: true}})
相关问题