Home > database >  Get Array containing objects to normal object which have value as key in MongoDb result
Get Array containing objects to normal object which have value as key in MongoDb result

Time:12-19

I have this in

[
  {
    "date": "2022-12-03T12:16:52.403Z",
    "configs": [
      {
        "name": "Shubham",
        "values": [
          {
            "text": "172cm",
            "type": "Height",
          },
          {
            "text": "80kg",
            "type": "Weight",
          },
          {
            "text": "male",
            "type": "Gender",
          },
        ],
      }
    ]
  },
  {....},{....}
]

Want to convert config into objects like this

[
  {
    "date": "2022-12-03T12:16:52.403Z",
    "configs": {
       "name": "Shubham",
       "Height": "172cm",
       "Weight": "80kg",
       "Gender": "male",
    }
  },
 {...},{...},
]

I know how to do in Javascript array map method but need to understand how to do in mongoDb query ($project).

CodePudding user response:

Did you try this?

arr=[];
yourOutPutJson.forEach(function(b){var obj={};obj.name=b.configs[0].name;b.configs[0].values.forEach(function(c){obj[c.type]=c.text});arr.push(obj)});

CodePudding user response:

Here is a possible approach

  1. First $unwind the configs since it contains only 1 element
  2. In the $project stage use $arrayToObject to convert the [{k:'key1',v:'value1'},{k:'key2',v:'value2'}] to {key1:'value1',key2:'value2'}.
  3. The $map stage is used to convert the field names in values array to the above format.
  4. $concatArrays is used to concat the name field and value before converting array to object so that it becomes [{k:'name',v:'Shubham'},{k:'Height',v:'172cm'}...]

Playground Link

db.collection.aggregate([
  {
    $unwind: "$configs"
  },
  {
    $project: {
      date: 1,
      configs: {
        $arrayToObject: {
          $concatArrays: [
            {
              $map: {
                input: "$configs.values",
                as: "el",
                in: {
                  k: "$$el.type",
                  v: "$$el.text"
                }
              }
            },
            [
              {
                k: "name",
                v: "$configs.name"
              }
            ]
          ]
        },
        
      },
      
    },
    
  },
  
])
  • Related