5

I've seen a lot of answers on how to sum properties of objects in arrays within the array, but I'm trying to sum individual properties on an object in an array across documents. For example, given this document structure:

{
   "id": 1,
   "stats": [
     {
       "number": 100,
       "year": 2014
     },
     {
       "number": 200,
       "year": 2015
     }
]
},


{
   "id": 2,
   "stats": [
     {
       "number": 50,
       "year": 2014
     },
     {
       "number": 75,
       "year": 2015
     }
]
}

The desired output would be:

{
   "stats": [
     {
       "number": 150,
       "year": 2014
     },
     {
       "number": 275,
       "year": 2015
     }
}

I don't want to sum the number property of 2014 and 2015, I want to sum it across 2014 for both documents.

2 Answers 2

8
db.test.aggregate([
   {  $unwind: "$stats" },
   {
        $group: {
            _id:"$stats.year",
            number:{$sum:"$stats.number"}
        }
    },
    { 
        $group: {
          _id: 0,  
          stats:{ $push:  {year:"$_id",number:"$number"}}
        }
    },
    {  
        $project:{stats:1,_id:0}
    } ])
Sign up to request clarification or add additional context in comments.

Comments

0

This will give you the desired output

db.getCollection('yourcollection').aggregate([
    { $unwind: "$stats" },
    { 
        $group: {
            _id: "$stats.year",
            number:{$sum:"$stats.number"}
        }
    },
    { 
        $group: {
          _id: null,  
          stats:{ $push:  {year:"$_id",number:"$number"}}
        }
    },
    {  
        $project:{stats:1,_id:0}
    }  
])

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.