$sum (Sum Accumulator)
Last updated: 2026-10-09
$sum (Sum Accumulator)
$sum is an accumulator computing the total of a specified field across a group (or a count when given the literal 1). It is used inside $group for sums/counts and in $project to sum array elements. As an expression it sums a specified expression across all input documents.
| Category | Accumulators |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
// sum inside $group
{ $group: { _id: <key>, total: { $sum: "$field" } } }
// count
{ $group: { _id: <key>, count: { $sum: 1 } } }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $sum: total and count per item
db.sales.aggregate([
{ $group: { _id: "$item", total: { $sum: "$price" }, count: { $sum: 1 } } }
])
Output:
{ "_id": "abc", "total": 25, "count": 2 }
{ "_id": "xyz", "total": 30, "count": 3 }
📌 Notes
- Non-numeric values are skipped
- $sum: 1 is the idiomatic way to count documents in a group
- In $group it accumulates across the group; in $project it can sum array elements
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat happens when $sum hits a string field?
AStrings and non-numeric values are skipped (no error). For strict handling, convert with $toInt/$toDouble or default with $ifNull.
QMust the $sum accumulator only be used inside $group?
AAs an accumulator it is specific to $group. However $sum also works as a plain aggregation expression, e.g. in $project to sum an array, with the same semantics.
QWhat does $sum return for an empty array?
AIt returns 0. In $group, if a group has no matching documents or an empty array, $sum accumulates to 0, which is handy as a counting fallback.