[英]MongoDB: How to merge all documents into a single document in an aggregation pipeline
I have the current aggregation output as follows:我的当前聚合输出如下:
[
{
"courseCount": 14
},
{
"registeredStudentsCount": 1
}
]
The array has two documents.该数组有两个文档。 I would like to combine all the documents into a single document having all the fields in mongoDB我想将所有文档组合成一个文档,其中包含 mongoDB 中的所有字段
{
$group: {
"_id": "null",
data: {
$push: "$$ROOT"
}
}
}
When you add this as the last pipeline, it will put all the docs under data, but here data would be an array of objects.当您将其添加为最后一个管道时,它会将所有文档放在 data 下,但这里的 data 将是一个对象数组。
In your case it would be在你的情况下,它会是
{ "data":[
{
"courseCount": 14
},
{
"registeredStudentsCount": 1
}
] }
Another approach would be,另一种方法是,
db.collection.aggregate([
{
$group: {
"_id": "null",
f: {
$first: "$$ROOT",
},
l: {
$last: "$$ROOT"
}
}
},
{
"$project": {
"output": {
"courseCount": "$f.courseCount",
"registeredStudentsCount": "$l.registeredStudentsCount"
},
"_id": 0
}
}
])
It's not dynamic as first one.它不像第一个那样动态。 As you have two docs, you can use this approach.由于您有两个文档,因此您可以使用这种方法。 It outputs它输出
[
{
"output": {
"courseCount": 14,
"registeredStudentsCount": 1
}
}
]
With extra pipeline in the second approach在第二种方法中使用额外的管道
{
"$replaceRoot": {
"newRoot": "$output"
}
}
You will get the output as你会得到输出为
[
{
"courseCount": 14,
"registeredStudentsCount": 1
}
]
db.collection.aggregate([
{
$group: {
_id: 0,
merged: {
$push: "$$ROOT"
}
}
},
{
$replaceRoot: {
newRoot: {
"$mergeObjects": "$merged"
}
}
}
])
Explained:解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.