如何在mongodb中将多个文档聚合到一个文档中

时间:2018-01-22 05:27:30

标签: mongodb

第一份文件

{
    "_id" : ObjectId("5a630d295a825ee130a8b124"),
    "name" : "xxx",
    "mobile" : NumberLong(0000000000)
}

第二份文件

{
    "_id" : ObjectId("5a630d665a825ee130a8b12e"),
    "state" : "Haryana",
    "mobile" : NumberLong(0000000000),
    "city" : "Safidon"
}

第三份文件

{
    "_id" : ObjectId("5a630d965a825ee130a8b137"),
    "mobile" : NumberLong(0000000000),
    "state" : "Haryana",
    "pincode" : 126112
}

我的代码为:

db.getCollection('demodata').aggregate([
{
    "$group": {
         "_id": "$mobile",
         "components": {
              "$push": {
                  "state":"$state",
                  "name":"$name",
                  "city":"$city",
                  "pincode":"$pincode"
              }
         }
    }
    },
     {
        "$project": {
            "_id": 0, "mobile": "$_id", "components": 1
        }
    },
     { "$out": "mytable" }
    ])

输出为:

{
    "_id" : ObjectId("5a65704d5a825ee130a8f137"),
    "components" : [ 
        {
            "name" : "xxx"
        }, 
        {
            "state" : "Haryana",
            "city" : "Safidon"
        }, 
        {
            "state" : "Haryana",
            "pincode" : 126112
        }
    ],
    "mobile" : NumberLong(0000000000)
}

我希望基于移动领域汇总

我想要结果为:

{
    "_id" : ObjectId("5a630d965a825ee130a8b19e"),
    "name" : "xxx",
    "mobile" : NumberLong(0000000000),
    "state" : "Haryana",
    "pincode" : 126112,
    "city" : "Safidon"
}

1 个答案:

答案 0 :(得分:0)

您可以在3.6中使用$mergeObjects

db.demodata.aggregate([
  {"$group":{
    "_id":"$mobile",
    "data":{
      "$mergeObjects":{
        "mobile":"$mobile",
        "state":"$state",
        "name":"$name",
        "city":"$city","pincode":"$pincode"
      }
    }
  }},
  {"$replaceRoot":{"newRoot":"$data"}},
  {"$out":"mytable"}
])

如果需要,我会添加3.4编辑。请告诉我。