0
0
MongoDBquery~30 mins

Arithmetic expressions ($add, $multiply, $divide) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the sales collection with product data
Create a MongoDB collection named sales with these exact documents: { product: "Pen", quantity: 10, price: 2 }, { product: "Notebook", quantity: 5, price: 4 }, and { product: "Eraser", quantity: 20, price: 1 }.
MongoDB
Need a hint?

Use db.sales.insertMany([...]) to add multiple documents at once.

2
Add a tax variable for the fixed tax amount
Create a variable named tax and set it to the number 5 to represent the fixed tax amount.
MongoDB
Need a hint?

Use const tax = 5 to create a fixed tax variable.

3
Calculate total revenue and add tax using $multiply and $add
Write a MongoDB aggregation pipeline that uses $multiply to multiply quantity and price to get total revenue, then uses $add to add the tax variable to this total. Use $project to output product and the calculated totalWithTax.
MongoDB
Need a hint?

Use $project to create a new field totalWithTax that adds tax to the product of quantity and price.

4
Divide the total with tax by 2 using $divide to get average revenue
Extend the aggregation pipeline to use $divide to divide totalWithTax by 2. Output the product and the result as averageRevenue.
MongoDB
Need a hint?

Use $divide inside $project to divide the sum by 2 and rename the field to averageRevenue.