Search code examples
mongodbaggregation-frameworkspring-data-mongodb

Is there any way to add dynamic field name in mongo DB aggregation.The field name is based on the data from the same collection


I want to add some new fields in my view creation logic.but the fields name will be concatenation of some existing field. so based on some condition i have to add those field in my view.

Example : data in my collection

{
data:{
computed_type:sleep
source:watch,
type:inBed,
value:60
}
}

I want to add field in my view with -> field name:field value

{
sleep_watch_inbed : 60
}

I have tried these, but not working

project:{

 dynamicKey: {
    $map:{
      input :  { $objectToArray: "$data" },
      as: "elem",
        in: {
      $cond: [
      {
        $eq: ["elem.computed_type", "sleep"],
      },
      {
        $concat: [ "sleep_", 'elem.type',"_",'elem.source' 
     ],
      },
      "$elem.computed_type",
    ]
        }
    }
   }
}

`


Solution

  • Not clear where you like to add the field. Could be this one:

    db.collection.aggregate([
       {
          $set: {
             data: {
                $concatArrays: [
                   { $objectToArray: "$data" },
                   [{
                      k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
                      v: "$data.value"
                   }]
                ]
             }
          }
       },
       { $set: { data: { $arrayToObject: "$data" } } }
    ])
    

    or this:

    db.collection.aggregate([
       {
          $set: {
             dynamicKey: [
                {
                   k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
                   v: "$data.value"
                }
             ]
          }
       },
       { $replaceWith: { $mergeObjects: ["$$ROOT", { $arrayToObject: "$dynamicKey" }] } },
       { $unset: "dynamicKey" }
    ])