$sum accumulator in MongoDB - Time & Space Complexity
When using the $sum accumulator in MongoDB, it's important to understand how the time to calculate the sum grows as the data size increases.
We want to know: how does the work change when we add more documents to sum?
Analyze the time complexity of the following MongoDB aggregation snippet.
db.sales.aggregate([
{ $group: { _id: "$store", totalSales: { $sum: "$amount" } } }
])
This groups sales by store and sums the amount for each store.
Look for repeated actions that take time.
- Primary operation: Summing the
amountfield for each document in the collection. - How many times: Once for each document in the input data.
As the number of documents grows, the sum operation must add more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of documents; double the documents means double the additions.
Time Complexity: O(n)
This means the time to compute the sum grows in a straight line with the number of documents.
[X] Wrong: "The $sum accumulator runs instantly no matter how many documents there are."
[OK] Correct: Each document's value must be added, so more documents mean more work and more time.
Understanding how aggregation operations like $sum scale helps you explain performance in real projects and shows you can think about data size impact clearly.
What if we changed the aggregation to group by two fields instead of one? How would the time complexity change?
Practice
$sum accumulator do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the role of
The$sum$sumaccumulator adds numeric values or counts documents when used in a$groupstage.Step 2: Compare with other accumulators
Unlike$avgwhich calculates averages,$sumonly totals values or counts documents.Final Answer:
Adds values together or counts documents within groups -> Option AQuick Check:
$sum= Adds or counts [OK]
- Confusing $sum with $avg
- Thinking $sum sorts data
- Assuming $sum filters documents
price in a $group stage?Solution
Step 1: Identify correct field reference syntax
In MongoDB aggregation, field names must be prefixed with "$" inside expressions, so "$price" is correct.Step 2: Check accumulator syntax
The accumulator must be$sum, notsum, and the value must be a string with "$" prefix.Final Answer:
{ $group: { _id: null, total: { $sum: "$price" } } } -> Option BQuick Check:
Use $sum with "$field" syntax [OK]
- Omitting the $ before field name
- Using sum instead of $sum
- Not quoting the field name
{ "category": "A", "value": 10 }{ "category": "A", "value": 20 }{ "category": "B", "value": 5 }What will be the output of this aggregation?
[{ $group: { _id: "$category", totalValue: { $sum: "$value" } } }]Solution
Step 1: Group documents by category
Documents with category "A" are grouped together, and category "B" separately.Step 2: Sum the "value" fields per group
For category "A": 10 + 20 = 30; for category "B": 5.Final Answer:
[{ "_id": "A", "totalValue": 30 }, { "_id": "B", "totalValue": 5 }] -> Option AQuick Check:
Sum values per category [OK]
- Summing without grouping
- Using null _id causing single group
- Adding only one document's value
[{ $group: { _id: "$type", total: { $sum: value } } }]What is the error in this pipeline?
Solution
Step 1: Check field reference inside $sum
The field 'value' must be referenced as "$value" (string with $ prefix) inside $sum.Step 2: Confirm correct $group usage
The $group stage is present and _id is correctly set to "$type".Final Answer:
Field name 'value' should be quoted and prefixed with $ inside $sum -> Option DQuick Check:
Use "$field" inside $sum [OK]
- Using unquoted field names inside $sum
- Thinking $sum can't be used in $group
- Misunderstanding _id usage
store and amount. You want to find the total sales per store but only for stores with total sales above 1000. Which aggregation pipeline correctly uses $sum and filters the results?Solution
Step 1: Group sales by store and sum amounts
The first stage groups documents by "store" and sums the "amount" field into "totalSales".Step 2: Filter groups with totalSales greater than 1000
The second stage uses $match on the aggregated field "totalSales" to keep only stores with totals above 1000.Final Answer:
[{ $group: { _id: "$store", totalSales: { $sum: "$amount" } } }, { $match: { totalSales: { $gt: 1000 } } }] -> Option CQuick Check:
Group then filter on sum field [OK]
- Filtering before grouping
- Filtering on original amount instead of totalSales
- Filtering on wrong field name
Ready to prove it?
Pass the test and this pattern moves unknown
