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