Calculate Total Sales Using $sum Accumulator in MongoDB
📖 Scenario: You work at a small online store. You have a collection of sales records. Each record shows the product name and the number of units sold. You want to find out the total units sold for all products combined.
🎯 Goal: Build a MongoDB aggregation query that uses the $sum accumulator to calculate the total units sold across all sales records.
📋 What You'll Learn
Create a collection called sales with documents containing product and units fields.
Add a variable to hold the aggregation pipeline.
Use the $group stage with _id: null and totalUnits field using $sum on units.
Complete the aggregation query to return the total units sold.
💡 Why This Matters
🌍 Real World
Stores and businesses often need to calculate total sales or quantities from many records to understand performance.
💼 Career
Knowing how to use MongoDB aggregation and the $sum accumulator is essential for data analysis roles and backend development involving NoSQL databases.
Progress0 / 4 steps
1
Create the sales collection with sample data
Create a variable called sales and assign it an array of documents with these exact entries: { product: "Pen", units: 10 }, { product: "Notebook", units: 5 }, { product: "Eraser", units: 3 }.
MongoDB
Hint
Use an array of objects with product and units fields exactly as shown.
2
Define the aggregation pipeline variable
Create a variable called pipeline and assign it an empty array to start building the aggregation pipeline.
MongoDB
Hint
Just create an empty array called pipeline to hold aggregation stages.
3
Add a $group stage using $sum accumulator
Add an object to the pipeline array with a $group stage. Use _id: null and create a field called totalUnits that uses $sum to add all units values from the sales documents.
MongoDB
Hint
Use $group with _id: null to aggregate all documents into one group. Use $sum: "$units" to add the units.
4
Complete the aggregation query
Create a variable called totalSales and assign it the result of calling sales.aggregate(pipeline) to run the aggregation pipeline and get the total units sold.
MongoDB
Hint
Use sales.aggregate(pipeline) to run the aggregation pipeline on the sales array.
Practice
(1/5)
1. What does the $sum accumulator do in a MongoDB aggregation pipeline?
easy
A. Adds values together or counts documents within groups
B. Finds the average value of a field
C. Sorts documents in ascending order
D. Filters documents based on a condition
Solution
Step 1: Understand the role of $sum
The $sum accumulator adds numeric values or counts documents when used in a $group stage.
Step 2: Compare with other accumulators
Unlike $avg which calculates averages, $sum only totals values or counts documents.
Final Answer:
Adds values together or counts documents within groups -> Option A
Quick Check:
$sum = Adds or counts [OK]
Hint: Remember: $sum totals numbers or counts docs [OK]
Common Mistakes:
Confusing $sum with $avg
Thinking $sum sorts data
Assuming $sum filters documents
2. Which of the following is the correct syntax to sum the field price in a $group stage?
D. Field name 'value' should be quoted and prefixed with $ inside $sum
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 D
Quick Check:
Use "$field" inside $sum [OK]
Hint: Always quote and prefix field with $ inside $sum [OK]
Common Mistakes:
Using unquoted field names inside $sum
Thinking $sum can't be used in $group
Misunderstanding _id usage
5. You have a collection of sales documents with fields 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?