【问题标题】:MongoDB object property $exists in nested arrayMongoDB 对象属性 $exists 在嵌套数组中
【发布时间】:2016-11-25 03:21:09
【问题描述】:

我的数据库集合中有以下对象结构:

{
    "name" : "test",
    "code" : "test",
    "attributes" : [ 
        {
            "name" : "test1",
            "code" : "code1"
        }, 
        {
            "name" : "test2",
            "code" : "code2",
            "value" : true
        }, 
        {
            "name" : "test3",
            "code" : "code3",
            "value" : ""
        }, 
        {
            "name" : "test4",
            "code" : "code4"
            "value" : [ 
                {
                    "code" : "code4.1",
                    "name" : "test4.1"
                }, 
                {
                    "name" : "test4.2"
                }
            ]
        }
    ]
}

所以“value”属性可以是空字符串、布尔值、数组,甚至根本没有定义。

如何查询具有非空属性数组且未在数组内至少一个对象中定义“attributes.value”属性的对象?

附言我尝试了以下查询:

db.collection.find({"attributes": {$exists: true, $ne: []}, "attributes.value": {$exists: false}})

但查询结果为空。

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query


    【解决方案1】:

    $elemMatch 运算符匹配包含数组字段的文档 至少有一个元素匹配所有指定的查询 标准。

    这个查询对我有用:

    db.getCollection('testeur').find({ "attributes": {
            $exists: true, 
            $ne: [],
            $elemMatch: { "value": {$exists: false } } 
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2020-10-29
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      相关资源
      最近更新 更多