0

Document 1: Need to covert object to Arrays. I have to iterate on each element of the key and value, how I can convert from an object to Array.

{
  "Data":{
    "A" :{
      "name" : alpha,
      "Score" : 199
    },
    "B" :{
      "name" : Beta,
      "Score" : 122
    }
  }
}

Expected Output :

{
  "name" :[
    alpha,
    Beta
  ],
  "score": [
    199,
    122
  ]
}

1 Answer 1

1

You can achieve this using mongo aggregation framework.

[
  {
    "$addFields": {
      "Data": {
        "$objectToArray": "$Data"
      }
    }
  },
  {
    $unwind: "$Data"
  },
  {
    "$group": {
      "_id": "_id",
      "name": {
        $push: "$Data.v.name"
      },
      "score": {
        $push: "$Data.v.Score"
      },
      
    }
  }
]

Mongo Playground: https://mongoplayground.net/p/JVTW5rEoJoa

Sign up to request clarification or add additional context in comments.

Comments

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.