简体   繁体   中英

MongoDB Aggregation: creating subdocuments

I have a MongoDB collection containing documents like these:

{
  "_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",
}

I want to $group them using the "code" field as _id, creating an array of subdocument containing parent_code and 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"
        }
    ]
}

Is it possible using the Aggregation Framework only? I haven't seen reference to subdocuments in the aggregation framework documentation, so I think it's not...

Thx you all.

You can use the following aggregation pipeline to achieve the desired result:

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

Output :

/* 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM