【问题标题】:Retrieve only the queried object from nested array in MongoDB仅从 MongoDB 中的嵌套数组中检索查询的对象
【发布时间】:2016-08-31 08:39:47
【问题描述】:

在我的 Mongo 中有以下文档,我正在尝试获取具有指定 ID 的对象。这是我的 Mongo 文档。 Mongo 版本:2.6

{
    "_id" : ObjectId("57c1ae9ac1bd31d4eb4d546d"),
    "footers" : [ 
        {
            "type" : "web",
            "rows" : [ 
                {
                    "id" : "abc",
                    "elements" : [ 
                        {
                            "id" : "def",
                            "type" : "image",
                            "url" : "http://example.com"
                        }, 
                        {
                            "id" : "ghi",
                            "type" : "image",
                            "url" : "http://example.com"
                        }
                    ]
                }
            ]
        }
    ]
}

我正在寻找一个id为“def”的对象,我想得到这个结果:

{
    "id" : "def",
    "type" : "image",
    "url" : "http://example.com"
}

下面我引用了我试图搜索这个对象的代码示例。

db.getCollection('myCollection').aggregate([
    {"$match": {
        "footers.rows.elements.id": "def"
    }},
    {"$group": {
        "_id": "$footers.rows.elements"
    }}
])

结果是:

{
    "_id" : [ 
        [ 
            [ 
                {
                    "id" : "def",
                    "type" : "image",
                    "url" : "http://example.com"
                }, 
                {
                    "id" : "ghi",
                    "type" : "image",
                    "url" : "http://example.com"
                }
            ]
        ]
    ]
}

有什么建议吗?

【问题讨论】:

    标签: mongodb aggregates


    【解决方案1】:

    您需要使用“$unwind”。

    此答案将帮助您了解更多详细信息Mongodb unwind nested documentshttps://stackoverflow.com/a/12241733/224743 指定这应该适用于 MongoDB 2.2+)

    对于您的具体示例,您可以执行以下操作:

    db.getCollection('myCollection').aggregate([
        {"$match"  : { "footers.rows.elements.id": "def" }}, 
        {"$unwind" : "$footers"}, 
        {"$unwind" : "$footers.rows"}, 
        {"$unwind" : "$footers.rows.elements"}, 
        {"$group"  : { "_id": "$footers.rows.elements" }}, 
        {"$match"  : { "_id.id": "def" }}
    ]);
    

    注意多个“$unwind”链接以及最终的“$match”,这是重新应用 $unwind-ed 文档的条件所必需的。

    【讨论】:

    • 非常感谢。很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 2018-09-10
    • 2018-11-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    相关资源
    最近更新 更多