1

I had asked this question here and I got a satisfactory answer. But I have a new problem that I am unable to solve.

The output I am getting from the query is an array of objects. How can I turn that array into an object? I already know how to do it in plain javascript but how can I do it in a mongodb aggregation query?

You can assume that you have the data below in the aggregation query.

[
    {  "choiceA": [
            {"_id": ObjectId("..."), "voter": "Juzi", "choice": 0, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Juma", "choice": 0, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Jane", "choice": 0, "pollId": 100 },
    ]},
    {  "choiceB": [
            {"_id": ObjectId("..."), "voter": "Jamo", "choice": 1, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Juju", "choice": 1, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Jana", "choice": 1, "pollId": 100 }
    ]},
    {  "choiceC": [ ] }
]

How do I turn it into an object to look like below

{
    "choiceA": [
            {"_id": ObjectId("..."), "voter": "Juzi", "choice": 0, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Juma", "choice": 0, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Jane", "choice": 0, "pollId": 100 },
    ],
    "choiceB": [
            {"_id": ObjectId("..."), "voter": "Jamo", "choice": 1, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Juju", "choice": 1, "pollId": 100 },
            {"_id": ObjectId("..."), "voter": "Jana", "choice": 1, "pollId": 100 }
    ],
    "choiceC": [ ] 
}

Or you can just answer this question with the result above as the output. Thank you.

0

1 Answer 1

1

Add these steps to your pipeline:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      x: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $project: {
      _id: 0,
      x: {
        $mergeObjects: "$x"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$x"
    }
  }
])

MongoPlayground

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

1 Comment

Hi @Valijon, Kindly check this other related question. Thank you.

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.