How to Use $sum in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation, use the
$sum operator to add values across documents or fields. It can sum numeric fields or count documents by using $sum: 1. Place $sum inside a $group stage to calculate totals grouped by a key.Syntax
The $sum operator is used inside the $group stage of an aggregation pipeline. It sums values of a specified field or counts documents.
{ $group: { _id: <grouping_key>, total: { $sum: <expression> } } }<grouping_key>is the field or expression to group by.<expression>is the field to sum or1to count documents.
json
{
$group: {
_id: <grouping_key>,
total: { $sum: <expression> }
}
}Example
This example groups sales by product and sums the quantity sold for each product.
javascript
db.sales.aggregate([
{
$group: {
_id: "$product",
totalQuantity: { $sum: "$quantity" }
}
}
])Output
[
{ "_id": "apple", "totalQuantity": 25 },
{ "_id": "banana", "totalQuantity": 40 },
{ "_id": "orange", "totalQuantity": 30 }
]
Common Pitfalls
Common mistakes include:
- Using
$sumoutside of$groupstage, which causes errors. - Summing non-numeric fields, resulting in null or errors.
- For counting documents, forgetting to use
$sum: 1inside$group.
javascript
/* Wrong: $sum used outside $group */ db.sales.aggregate([ { $sum: "$quantity" } ]) /* Right: $sum inside $group */ db.sales.aggregate([ { $group: { _id: null, totalQuantity: { $sum: "$quantity" } } } ])
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Sum field values | Adds numeric values of a field | { $sum: "$fieldName" } |
| Count documents | Counts number of documents in group | { $sum: 1 } |
| Group by field | Groups documents by a field | { _id: "$fieldName" } |
Key Takeaways
Use $sum inside $group to add values or count documents.
To count documents, use $sum: 1.
Ensure the field summed contains numeric values.
Do not use $sum outside aggregation stages like $group.
Group by a field using _id in $group stage.