MongoDB Aggregation Sum on Objects in Array

前端 未结 2 1118
小蘑菇
小蘑菇 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: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}
        }  
    ])
    

提交回复
热议问题