I have a mongo document like below;
{
"_id" : "123",
"info" : {
"batch" : "Batch1-Minor"
},
"batchElements" : {
"elements" : [
{
"_id" : "elementId1",
"type": "ABC"
},
{
"_id" : "elementId2",
"type": "ABC"
}
]
}
}
How can generate an aggregated output by changing the _id field inside elements by concatenating $info.batch and $batchElements.elements._id
Expected Output:
{
"_id" : "123",
"info" : {
"batch" : "Batch1-Minor"
},
"batchElements" : {
"elements" : [
{
"_id" : "Batch1-Minor-elementId1",
"type": "ABC"
},
{
"_id" : "Batch1-Minor-elementId2",
"type": "ABC"
}
]
}
}
With below query we're iterating through batchElements.elements & forming objects with type & _id & finally $map would push an array of objects back to batchElements.elements where $addFields would add the field to actual document, Try this :
db.yourCollectionName.aggregate([{
$addFields: {
'batchElements.elements': {
$map:
{
input: "$batchElements.elements",
as: "each",
in: { type: '$$each.type', '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }
/** So if you've multiple fields in each object then instead of listing all, You need to use
in: { $mergeObjects: ["$$each", { '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }] } */
}
}
}
}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With