【问题标题】:Select MongoDB documents where a field either does not exist, is null, or is false?选择字段不存在、为空或为假的 MongoDB 文档?
【发布时间】:2014-04-12 23:42:32
【问题描述】:

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

{ "_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”为空或不存在的文档,但仍不会选择“is_reported”为假的文档。

现在我有以下查询,它工作正常,但它看起来不是很优雅。如果我需要选择多个字段,它会很快变得混乱。是否有更好的查询可以达到相同的最终结果?

db.fruits.find({ $or: [ { "is_reported": null }, { "is_reported": false } ] })

【问题讨论】:

    标签: mongodb mongodb-query database


    【解决方案1】:

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

    【讨论】:

    • 是否查询字段不存在的文档?
    • @wbeange 是的,null 查询值也匹配不存在该字段的文档。
    猜你喜欢
    • 2017-05-15
    • 2022-01-09
    • 1970-01-01
    • 2021-12-02
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    相关资源
    最近更新 更多