Rohitesh
Rohitesh

Reputation: 1624

Merge Multiple Document from same collection MongoDB

I have a JSON data like this and i wanted to apply aggregation on this data in such a way that i should group by from data:

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

and i have acheived this by the above aggregation:

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

OutPut:

{
    "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
}

But, i am getting two document and this i want to merge as a single document like :

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

Can anyone help me on this.

Upvotes: 0

Views: 2005

Answers (1)

Mukesh Saini
Mukesh Saini

Reputation: 1498

Add following $group at the end of your aggregate pipeline to merge current output documents into single document -

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

Upvotes: 1

Related Questions