Reputation: 535
I have an aggregated mongo document like below. There are two different batches ("-Minor" and "-Major"), and each batch has "batchElements" too.
{
"_id" : "123",
"info" : {
"batch" : "Batch1-Minor"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
},
{
"_id" : "123",
"info" : {
"batch" : "Batch2-Minor"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
},
{
"_id" : "123",
"info" : {
"batch" : "Batch3-Major"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
},
{
"_id" : "123",
"info" : {
"batch" : "Batch4-Major"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
}
How can I collect all "batchElements" of "-Minor" and "-Major" and create a document as below;
Output:
{
"_id" : "123",
"minorElements" : [
[{}, {}, {}, ..... {} ], // elements of "Batch1-Minor"
[{}, {}, {}, ..... {} ], // elements of "Batch2-Minor"
... // elements of "BatchN-Minor"
],
"majorElements" : [
[{}, {}, {}, ..... {} ], // elements of "Batch3-Major"
[{}, {}, {}, ..... {} ], // elements of "Batch4-Major"
... // elements of "BatchN-Major"
]
}
Upvotes: 3
Views: 769
Reputation: 49945
You can start with $split to get the "type" of your batch as part of your $group _id
. Then you can run another $group
to make minor
and major
parts of the same document. In the last step you need $replaceRoot along with $arrayToObject to promote both arrays into root level.
db.collection.aggregate([
{
$group: {
_id: {
id: "$_id",
type: { $arrayElemAt: [ { $split: [ { $toLower: "$info.batch" }, "-" ] }, 1 ] }
},
docs: { $push: "$batchElements.elements" }
}
},
{
$group: {
_id: "$_id.id",
data: { $push: { k: { $concat: ["$_id.type","Elements"] }, v: "$docs" } }
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [ { _id: "$_id" }, { $arrayToObject: "$data" } ]
}
}
}
])
Upvotes: 2