如何在mongodb聚合中将对象数组转换为对象 [英] 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.
我从查询获得的输出是对象数组.如何将该数组转换为对象?我已经知道如何使用普通的javascript ,但是如何在mongodb聚合查询中做到这一点?
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"
}
}
])
这篇关于如何在mongodb聚合中将对象数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!