2

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.

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.