MongoDB聚合:创建子文档

时间:2015-04-27 09:40:24

标签: mongodb mongodb-query aggregation-framework

我有一个MongoDB集合,其中包含以下文档:

{
  "_id": ObjectId("..."),
  "code": 22726,
  "parent_code": 35481,
  "parent_description": "posterdati",
},
{
  "_id": ObjectId("..."),
  "code": 22726,
  "parent_code": 35484,
  "parent_description": "vicesindaco",
},
{
  "_id": ObjectId("..."),
  "code": 22727,
  "parent_code": 35487,
  "parent_description": "prefettura",
}

我想使用"代码"对它们进行分组。字段为_id,创建包含parent_code和parent_description的子文档数组:

{
    "code": 22726,
    parents: [
        {
            "parent_code": 35481,
            "parent_description": "posterdati"
        },
        {
            "parent_code": 35484,
            "parent_description": "vicesindaco"
        }
    ]
},
{
    "code": 22727,
    parents: [
        {
            "parent_code": 35487,
            "parent_description": "prefettura"
        }
    ]
}

是否可以仅使用聚合框架?我没有在聚合框架文档中看到对子文档的引用,所以我认为它不是......

谢谢大家。

1 个答案:

答案 0 :(得分:1)

您可以使用以下聚合管道来实现所需的结果:

db.collection.aggregate([
    {
        "$group": {
            "_id": "$code",
            "parents": {
                "$addToSet": {
                    "parent_code": "$parent_code",
                    "parent_description": "$parent_description"
                }
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "code": "$_id",
            "parents": 1
        }
    }
]);

<强>输出

/* 0 */
{
    "result" : [ 
        {
            "parents" : [ 
                {
                    "parent_code" : 35487,
                    "parent_description" : "prefettura"
                }
            ],
            "code" : 22727
        }, 
        {
            "parents" : [ 
                {
                    "parent_code" : 35484,
                    "parent_description" : "vicesindaco"
                }, 
                {
                    "parent_code" : 35481,
                    "parent_description" : "posterdati"
                }
            ],
            "code" : 22726
        }
    ],
    "ok" : 1
}