Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 363
Sahat Yalkabov Avatar asked Jun 11 '13 12:06

Sahat Yalkabov


People also ask

How do I count aggregates in MongoDB?

MongoDB aggregate $count queryIt transfers a document to the next stage that contains a count of the number of documents input to the stage. Here, the string is the name of the output field which has the count as its value. And, the string must be a non-empty string, not start with '$' and not contain '.

How can I get total number in MongoDB?

Description. n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB connection. n = count( conn , collection ,'Query', mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.

How do you count aggregates?

Returns as a BIGINT the number of rows in each group where the expression is not NULL . If the query has no GROUP BY clause, COUNT returns the number of table rows. The COUNT aggregate function differs from the COUNT analytic function, which returns the number over a group of rows within a window.

How do you sum a column in MongoDB?

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.


1 Answers

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.

like image 75
WiredPrairie Avatar answered Sep 30 '22 07:09

WiredPrairie