$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.

CategoryAccumulators
MongoDB Version1.0+
Example Languagemongosh (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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏