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.

YulePale
  • 6,688
  • 16
  • 46
  • 95

1 Answers1

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

Valijon
  • 12,667
  • 4
  • 34
  • 67
  • Hi @Valijon, Kindly check this other [related question](https://stackoverflow.com/q/62878339/9953550). Thank you. – YulePale Jul 14 '20 at 06:19