[英]How to turn an array of objects into an object in mongodb aggregation
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?我已经知道如何在普通的 javascript 中做到这一点,但如何在 mongodb 聚合查询中做到这一点?
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"
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.