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

huangapple go评论127阅读模式
英文:

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

问题

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

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",
    ]
        }
    }
   }
}

`

答案1

得分: 0

请查看以下代码段中的部分:

第一个代码段:

{
    k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
    v: "$data.value"
}

第二个代码段:

{
    k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
    v: "$data.value"
}
英文:

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" }
])

huangapple
  • 本文由 发表于 2023年4月11日 14:06:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定