Reputation: 890
How do I go about using mongodb aggregation pipeline to get the end result?
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!
Upvotes: 1
Views: 435
Reputation: 75924
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.
$replaceRoot
to promote the results as top.
db.colname.aggregate([
{"$group":{
"_id":null,
"results":{"$mergeObjects":{"$arrayToObject":[[["$_id","$Count"]]]}}
}},
{"$replaceRoot":{"newRoot":"$results"}}
])
Upvotes: 1