skip to Main Content

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).

2

Answers


  1. 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)});
    
    Login or Signup to reply.
  2. 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"
                  }
                ]
              ]
            },
            
          },
          
        },
        
      },
      
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search