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?
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
.
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 '.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With