How to aggregate sum in MongoDB to get a total count?

前端 未结 1 765
清歌不尽
清歌不尽 2020-11-27 04:19

For some collection with a field { wins: Number }, how could I use MongoDB Aggregation Framework to get the total number of wins across all documents i

相关标签:
1条回答
  • 2020-11-27 04:47

    Sum

    To get the sum of a grouped field when using the Aggregation Framework of MongoDB, you'll need to use $group and $sum:

    db.characters.aggregate([ { 
        $group: { 
            _id: null, 
            total: { 
                $sum: "$wins" 
            } 
        } 
    } ] )
    

    In this case, if you want to get the sum of all of the wins, you need to refer to the field name using the $ syntax as $wins which just fetches the values of the wins field from the grouped documents and sums them together.

    Count

    You can sum other values as well by passing in a specific value (as you'd done in your comment). If you had

    { "$sum" : 1 },

    that would actually be a count of all of the wins, rather than a total.

    0 讨论(0)
提交回复
热议问题