合并来自同一集合MongoDB的多个文档

时间:2017-05-18 05:09:01

标签: mongodb mongodb-query aggregation-framework

我有这样的JSON数据,我希望以这样的方式对这些数据应用聚合:我应该从数据中分组:

{
  "series": [
    {
     "id": "1",
      "element": "111",
      "data": [
        {
          "timeFrame": {
            "from": "2016-01-01T00:00:00Z",
            "to": "2016-01-31T23:59:59Z"
          },
          "value": 1
        },
        {
          "timeFrame": {
            "from": "2016-02-01T00:00:00Z",
            "to": "2016-02-29T23:59:59Z"
          },
          "value": 2
        }
      ]
    }
  ]
}

我通过以上聚合实现了这一点:

db.getCollection('col1').aggregate([
{$unwind: "$data"},
{$group :{
    element: {$first:"$relatedElement"},
    _id : {
        day : {$dayOfMonth: "$values.timeFrame.from"},
        month:{$month: "$values.timeFrame.from"},
        year:{$year: "$values.timeFrame.from"}
    },
    fromDate : { $first : "$values.timeFrame.from" },
    total : {$sum : "$values.value"},
    count : {$sum : 1},
 }
},
{ 
  $project: {  
      _id : 0,
      element:1,
      fromDate  : '$fromDate', 
      avgValue : { $divide: [ "$total", "$count" ] }
    }
}]) 

输出:

{
    "id" : "1",
    "element" : "3",
    "fromDate" : ISODate("2017-05-01T00:00:00.000Z"),
    "avgValue" : 0.0378787878787879
}

{
    "id" : "1",
    "element" : "3",
    "fromDate" : ISODate("2017-04-30T22:00:00.000Z"),
    "avgValue" : 0.416666666666667
}

但是,我得到两个文件,我希望合并为单个文档,如:

{
    "id" : "1",
    "element" : "3",
    "average" : [
    {
    "fromDate" : ISODate("2017-05-01T00:00:00.000Z"),
    "avgValue" : 0.0378787878787879
    },
    {
    "fromDate" : ISODate("2017-04-30T22:00:00.000Z"),
    "avgValue" : 0.416666666666667
    }
    ]
}

任何人都可以帮我这个。

1 个答案:

答案 0 :(得分:0)

在聚合管道的末尾添加以下$group,以将当前输出文档合并到单个文档中 -

{$group:{
    _id:"$_id",
    element: {$first: "$element"},
    average:{$push:{
      "fromDate": "$fromDate",
      "avgValue": "$avgValue"
    }}
}}