MongoDB Aggregation Sum on Objects in Array

前端 未结 2 1103
小蘑菇
小蘑菇 2021-01-01 07:47

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 docu

相关标签:
2条回答
  • 2021-01-01 08:04
    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}
        } ])
    
    0 讨论(0)
  • 2021-01-01 08:14

    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}
        }  
    ])
    
    0 讨论(0)
提交回复
热议问题