What if you could add thousands of numbers perfectly with just one simple command?
Why $sum accumulator in MongoDB? - Purpose & Use Cases
Imagine you have a huge list of sales records in a spreadsheet. You want to find out the total sales amount for each product. Doing this by hand means adding up hundreds or thousands of numbers manually or copying them into a calculator one by one.
Manually adding numbers is slow and tiring. It's easy to make mistakes like skipping a row or adding the wrong number. If the data changes, you have to start all over again. This wastes time and causes frustration.
The $sum accumulator in MongoDB automatically adds up values for you inside the database. It quickly totals numbers across many documents without errors. You just tell it what to add, and it does the math instantly.
total = 0 for record in sales: total += record['amount'] print(total)
db.sales.aggregate([{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } }])It lets you easily calculate totals and sums across large datasets instantly, unlocking powerful data insights.
A store owner uses $sum to find total sales per product category each day, helping decide which items to restock.
Manually adding numbers is slow and error-prone.
$sum automates adding values inside MongoDB.
This saves time and gives quick, accurate totals for data analysis.
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
