Reputation: 85
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.
Upvotes: 2
Views: 1539
Reputation: 103375
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
}
Upvotes: 1