0
0
MongoDBquery~5 mins

$sum accumulator in MongoDB

Choose your learning style9 modes available
Introduction

The $sum accumulator helps add up numbers in a group. It is useful to find totals easily.

When you want to find the total sales amount from many sales records.
When you need to count how many items were sold in each category.
When you want to add up points scored by players in a game.
When you want to calculate the total expenses from a list of transactions.
Syntax
MongoDB
{ $group: { _id: <grouping_key>, total: { $sum: <expression> } } }

The $sum can add values from a field or count documents if used with 1.

The _id defines how documents are grouped before summing.

Examples
Groups documents by category and sums the amount field for each group.
MongoDB
{ $group: { _id: "$category", totalSales: { $sum: "$amount" } } }
Counts how many documents are in each status group by adding 1 for each document.
MongoDB
{ $group: { _id: "$status", count: { $sum: 1 } } }
Sample Program

This query groups sales by item name and sums the quantity sold for each item.

MongoDB
db.sales.aggregate([
  { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } }
])
OutputSuccess
Important Notes

If the field used in $sum is missing or null in a document, it counts as zero.

You can use $sum inside $group or $project stages depending on your need.

Summary

$sum adds numbers or counts documents in groups.

Use it inside $group to get totals per group.

It helps quickly find totals like sales, counts, or points.