0

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
  • you want to change the format after you query ? if so you can this with an array map Commented Dec 19, 2022 at 8:06
  • Hey @cmgchess, i know how to do in JS array method, but wanted to learn how to do same thing in mongo query Commented Dec 19, 2022 at 8:09

2 Answers 2

1

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"
              }
            ]
          ]
        },
        
      },
      
    },
    
  },
  
])
Sign up to request clarification or add additional context in comments.

Comments

0

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)});

2 Comments

I know how to do in JS array method, but wanted to learn how to do same thing in mongo query
Please remove the javascript tag from the question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.