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.
Add these steps to your pipeline:
db.collection.aggregate([
{
$group: {
_id: null,
x: {
$push: "$$ROOT"
}
}
},
{
$project: {
_id: 0,
x: {
$mergeObjects: "$x"
}
}
},
{
$replaceRoot: {
newRoot: "$x"
}
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.