【问题标题】:query document by field in nested array that may not exist按可能不存在的嵌套数组中的字段查询文档
【发布时间】:2016-06-10 20:20:45
【问题描述】:

我有一个文档代表这样的规则结构

{
    "id" : "34534",
    "name" : "rule1",
    "parameters" : {
        "nodes" : [
            {
                "type" : "x",
                "properties" : {
                    "dataSets" : [
                        {
                            "dataSetKey" : "key"
                        },
                        {
                            "dataSetKey" : "key2"
                        }
                    ],
                    "resource" : {
                        "id" : "4353454"
                    }
                }
            },
            {
                "type" : "y",
                "params" : {}        
            }
        ]
    }
}

我想编写一个查询,如果它有一个类型为 x 的节点,则返回整个文档,并且在该节点内它有一个 dataSet,其 dataSetKey 为“key”。除非节点是 x 类型,否则它不会有包含 dataSets 数组的属性字段。我试过这个查询,但它返回 0 个文档

db.getCollection('Rules').find({
    "parameters.nodes": {
        $elemMatch: {
            "type": "x",
            "properties.dataSets": {
                $elemMatch: {
                    "dataSetKey": "key"
                }
            }
        }
    }
})

我也试过了

db.getCollection('Rules').find({"parameters.nodes.properties.datasets": {$exists: true}},{
    "parameters.nodes": {
        $elemMatch: {
            "type": "x",
            "properties.dataSets": {
                $elemMatch: {
                    "dataSetKey": "key"
                }
            }
        }
    }
})

但它返回以下错误。

"$err" : "Cannot use $elemMatch projection on a nested field (currently unsupported)."

非常感谢任何帮助。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    我想知道它是否与 mongo 版本有关?我运行了您的第一个查询,结果确实得到了 1 个文档。

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 1970-01-01
      • 2015-04-24
      • 2018-09-04
      • 2019-10-09
      • 1970-01-01
      • 2020-11-28
      • 2021-07-21
      • 1970-01-01
      相关资源
      最近更新 更多