0
0
MongoDBquery~10 mins

$sum accumulator in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $sum accumulator
Start with empty sum = 0
Read each document's value
Add value to sum
Repeat for all documents
Output total sum
The $sum accumulator adds up values from each document in a group and outputs the total sum.
Execution Sample
MongoDB
db.sales.aggregate([
  { $group: { _id: null, totalSales: { $sum: "$amount" } } }
])
This query sums the 'amount' field from all documents in the 'sales' collection.
Execution Table
StepDocument amountCurrent sumActionSum after action
11000Add 100 to sum100
2200100Add 200 to sum300
350300Add 50 to sum350
4150350Add 150 to sum500
5-500No more documentsFinal sum = 500
💡 All documents processed, sum accumulator outputs 500
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
sum0100300350500500
Key Moments - 2 Insights
Why does the sum start at 0 before adding any values?
The sum accumulator initializes at 0 to correctly add values from documents. See execution_table row 1 where sum is 0 before adding the first amount.
What happens if a document's amount field is missing or null?
If the amount is missing or null, $sum treats it as 0 and does not change the sum. This is why each addition explicitly adds the document's amount value if present.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the sum after processing the second document?
A100
B200
C300
D350
💡 Hint
Check the 'Sum after action' column at step 2 in the execution_table.
At which step does the sum reach 500?
AStep 3
BStep 4
CStep 5
DStep 2
💡 Hint
Look at the 'Sum after action' column and find when it first shows 500.
If the third document's amount was 0 instead of 50, what would the sum be after step 3?
A300
B350
C250
D500
💡 Hint
Refer to variable_tracker and consider how sum changes when adding 0 instead of 50.
Concept Snapshot
$sum accumulator in MongoDB groups documents and adds values.
Starts at 0, adds each document's field value.
Ignores missing or null values as 0.
Outputs total sum after processing all documents.
Full Transcript
The $sum accumulator in MongoDB is used to add up values from documents in a group. It starts with a sum of zero. For each document, it reads the value of the specified field and adds it to the sum. This continues until all documents are processed. If a document does not have the field or it is null, it adds zero. The final output is the total sum of all values. For example, if documents have amounts 100, 200, 50, and 150, the sum accumulates as 100, then 300, then 350, and finally 500. This process helps quickly calculate totals in aggregation queries.