92

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.

4
  • Use a $group operation as shown in the docs. Commented Jun 11, 2013 at 12:54
  • @JohnnyHK I've tried db.characters.aggregate([{$group:{_id:'id',wins:{$sum:1}}}]); but without any luck. It returns how many wins fields i have instead of values from the wins. Commented Jun 11, 2013 at 13:19
  • 11
    db.characters.aggregate( [ { $group: { _id: null, total: { $sum: "$wins" } } } ] ) Commented Jun 11, 2013 at 13:22
  • 1
    @WiredPrairie Thank you it worked. Do you want to post it as an answer so I could accept it? Commented Jun 11, 2013 at 13:24

1 Answer 1

204

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.

Sign up to request clarification or add additional context in comments.

6 Comments

What would you do if this query takes a long time? (runs across many documents)
As this algorithm must scan every document, you'll need to resort to caching, precalculation, or filtering the results to reduce the overall time spent.
How do you get the result? I get a cursor back.
Why do you need the [ ] ? It works without them, i.e. db.characters.aggregate({$group ... }) instead of db.characters.aggregate([{$group ... }]) .
Wow, _id: null is the key here. +1 you tried to use the aggregation framework without thinking about using _id: null.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.