Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB concat two fields using aggregation where actual field is in an array

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"
             }
        ]
    }
}
like image 680
Boat Avatar asked Nov 24 '25 11:11

Boat


1 Answers

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"] } }] } */
            }
        }
    }
}])
like image 95
whoami - fakeFaceTrueSoul Avatar answered Nov 27 '25 03:11

whoami - fakeFaceTrueSoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!