0

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.

1 Answer 1

1

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"
    }}
}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.