【问题标题】:MongoDB query for null using dot syntaxMongoDB使用点语法查询空值
【发布时间】:2019-05-20 14:16:53
【问题描述】:

我无法使用dot syntax of mongo 在 mongodb 中查询空值。

数据库中的一些东西:

db.things.insertMany([
   { a: [{ value: 1 }] },
   { a: [{ value: null }] },
   { a: [{ value: 2 }] }
]);

我想查找所有在“a”数组中第一个元素为空值的文档。

查询:

db.getCollection('things').count({ "a.0.value": 1 }) => 1(如预期) db.getCollection('things').count({ "a.0.value": null }) => 3 (我也希望这里有 1 个)

我有点不知所措,为什么这会返回第二个查询的所有元素。它似乎只对数组索引结果有这种行为,这也让它有点奇怪。 (例如db.getCollection('things').count({ "a": null }) => 0 符合预期)

我唯一能想到的是,当它的值为 null 但我不知道如何解决这个问题时,它基本上取消了整个语句。

MongoDB v3.4.10

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用$expr 来使用聚合运算符,然后使用$arrayElemAt 找到第一个索引,即$equal to null

    db.collection.find({ "$expr": { "$eq": [{ "$arrayElemAt": ["$a.value", 0] }, null] } })
    

    MongoPlayground

    对于 3.6

    之前的 mongo 版本
    db.collection.aggregate([
      { "$addFields": {
        "match": { "$arrayElemAt": ["$a.value", 0] }
      }},
      { "$match": { "match": null }}
    ])
    

    MongoPlayground

    如果您甚至想检查 .dot 语法,那么您必须使用 $type 运算符与 null 值进行比较

    db.collection.find({ "a.0.value": { "$type": 10 } })
    

    MongoPlayground

    【讨论】:

    • 嘿,我认为如果我在较新的 mongo 中会起作用,但我在 3.4.10 中。你知道那个版本是否有类似的东西吗?
    • 实际上,即使使用 3.6,我也没有得到该查询的结果(我使用这个 repl:docs.mongodb.com/v3.6/tutorial/query-for-null-fields
    • 你知道为什么点语法适用于其他事物但不能为空吗?
    • 再次更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 2017-02-25
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2015-08-09
    • 2017-05-12
    • 1970-01-01
    相关资源
    最近更新 更多