简体   繁体   English

将文档合并为单个文档

[英]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.

相关问题 MongoDB:如何将所有文档合并到聚合管道中的单个文档中 - MongoDB: How to merge all documents into a single document in an aggregation pipeline 将 MongoDB 多个文档输出合并到单个文档 - Merge MongoDB multiple documents output to single documents 如何将许多文档合并为一个文档并移至另一个集合? - How can I merge many documents into a single document and move to another collection? 将多个文档合并为一个文档,其中包含 MongoDB 中的两个文档字段 - merge multiple documents into one document with both document fields in MongoDB 对包含文档列表的单个文档使用mongoimport - Using mongoimport with a single document containing a list of documents 多个文档或单个文档中的 arrays - Multiple documents or arrays within a single document Mongodb - 如何在第二个文档中按键连接两个文档并将子文档作为数组合并到父文档 - Mongodb - How to Join two documents by key in second document and merge child documents as array to parent document 更新单个文档(包含子数组文档)的单个更新查询? - Single update query to update a single document (containing subarray documents)? 如何将单个集合的多个文档合并为一个文档? - How to combine multiple documents of single collecton in to a single Document? 如何将异构数组合并到MongoDb中的单个文档? - How to merge a heterogeneous array to a single document in MongoDb?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM