Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

aggregation framework - How to aggregate sum in MongoDB to get a total count?

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 in a collection?

Example:

If I have 3 documents with wins: 5, wins: 8, wins: 12 respectively, how could I use MongoDB Aggregation Framework to return the total number, i.e. total: 25.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...