[英]Merge documents into single document
How do I go about using mongodb aggregation pipeline to get the end result?如何使用 mongodb 聚合管道来获得最终结果?
I have the following documents我有以下文件
{
"_id" : "aaa",
"Count" : 137.0
}
{
"_id" : "bbb",
"Count" : 11.0
}
{
"_id" : "ccc",
"Count" : 236.0
}
I need to merge them into a single document that looks like this..我需要将它们合并成一个看起来像这样的文档..
{
aaa: 137,
bbb: 11,
ccc: 236
}
Thank you!谢谢!
You can use below aggregation.您可以使用以下聚合。
Use $arrayToObject
to convert the arrays with value into object followed by $mergeObjects
to merge all the documents into single document.使用
$arrayToObject
将有值的数组转换为对象,然后使用$mergeObjects
将所有文档合并为单个文档。
$replaceRoot
to promote the results as top. $replaceRoot
将结果提升为顶级。
db.colname.aggregate([
{"$group":{
"_id":null,
"results":{"$mergeObjects":{"$arrayToObject":[[["$_id","$Count"]]]}}
}},
{"$replaceRoot":{"newRoot":"$results"}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.