简体   繁体   中英

Merge documents into single document

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!

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"}}
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM