仅从MongoDB中的嵌套数组中检索查询的对象

仅从MongoDB中的嵌套数组中检索查询的对象,mongodb,aggregates,Mongodb,Aggregates,在我的Mongo中有以下文档,我正在尝试获取具有指定id的对象。这是我的Mongo文档。 Mongo版本:2.6 { "_id" : ObjectId("57c1ae9ac1bd31d4eb4d546d"), "footers" : [ { "type" : "web", "rows" : [ { "id" : "abc",

在我的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 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”链接,以及为$unwind ed文档重新应用条件所需的最终“$match”。

非常感谢。非常有用。