Using Arithmetic Expressions in MongoDB Aggregation
📖 Scenario: You work in a small store that keeps product sales data in a MongoDB collection. You want to calculate the total revenue for each product by multiplying the quantity sold by the price per unit. You also want to add a fixed tax amount to the total revenue and then divide the final amount by 2 to find the average revenue over two months.
🎯 Goal: Build a MongoDB aggregation pipeline that uses the arithmetic expressions $add, $multiply, and $divide to calculate the average revenue including tax for each product.
📋 What You'll Learn
Create a collection named
sales with documents containing product, quantity, and price fields.Add a fixed tax amount variable named
tax with the value 5.Use
$multiply to calculate total revenue by multiplying quantity and price.Use
$add to add the tax to the total revenue.Use
$divide to divide the sum by 2 to get the average revenue.Output the product name and the calculated average revenue as
averageRevenue.💡 Why This Matters
🌍 Real World
Stores and businesses often need to calculate revenues, taxes, and averages from sales data stored in databases like MongoDB.
💼 Career
Understanding MongoDB aggregation and arithmetic expressions is essential for data analysts and backend developers working with NoSQL databases.
Progress0 / 4 steps