Pipeline Execution Order Matters in MongoDB Aggregation
📖 Scenario: You are managing a small online bookstore database. You want to analyze book sales data to find the total sales for books priced above a certain amount.
🎯 Goal: Build a MongoDB aggregation pipeline that first filters books priced above 20, then calculates the total sales for each book by multiplying price and quantity sold, and finally sorts the results by total sales in descending order.
📋 What You'll Learn
Create a collection named books with documents containing title, price, and quantity_sold fields.
Add a variable priceThreshold set to 20 to filter books priced above this value.
Write an aggregation pipeline that first filters books with price greater than priceThreshold.
Then add a field totalSales calculated as price * quantity_sold.
Finally, sort the results by totalSales in descending order.
💡 Why This Matters
🌍 Real World
Online stores and inventory systems often need to analyze sales data by filtering, calculating totals, and sorting results to make business decisions.
💼 Career
Understanding MongoDB aggregation pipelines and the importance of stage order is essential for backend developers and data analysts working with NoSQL databases.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert these exact documents: { title: "Book A", price: 15, quantity_sold: 10 }, { title: "Book B", price: 25, quantity_sold: 5 }, { title: "Book C", price: 30, quantity_sold: 7 }.
MongoDB
Hint
Use db.books.insertMany() with an array of objects containing the exact fields and values.
2
Set the priceThreshold variable
Create a variable called priceThreshold and set it to 20 to use as the filter value for book prices.
MongoDB
Hint
Use const priceThreshold = 20 to create the variable.
3
Build the aggregation pipeline with filtering and adding totalSales
Write an aggregation pipeline on books that first filters documents where price is greater than priceThreshold using $match, then adds a new field totalSales calculated as price * quantity_sold using $addFields.
MongoDB
Hint
Use $match first to filter, then $addFields to add totalSales as { $multiply: ["$price", "$quantity_sold"] }.
4
Add sorting stage to the aggregation pipeline
Add a $sort stage to the existing pipeline that sorts documents by totalSales in descending order.
MongoDB
Hint
Add { $sort: { totalSales: -1 } } as the last stage in the pipeline array.
Practice
(1/5)
1. In MongoDB aggregation pipelines, why does the order of stages matter?
easy
A. Because stages run in the order they are written, affecting results and performance
B. Because MongoDB runs all stages in parallel regardless of order
C. Because only the last stage affects the output
D. Because stages can be reordered automatically by MongoDB
Solution
Step 1: Understand pipeline execution
MongoDB executes pipeline stages sequentially in the order they appear.
Step 2: Impact of order on results and performance
Changing the order can change the output and how fast the query runs, especially filtering early helps performance.
Final Answer:
Because stages run in the order they are written, affecting results and performance -> Option A
Quick Check:
Pipeline order affects output and speed [OK]
Hint: Remember: pipeline stages run top to bottom [OK]
Common Mistakes:
Thinking MongoDB runs stages in parallel
Believing order does not affect output
Assuming MongoDB reorders stages automatically
2. Which of the following is the correct syntax to start a MongoDB aggregation pipeline with a filter stage?
easy
A. db.collection.aggregate([{ $match: { status: 'A' } }])
B. db.collection.aggregate({ $match: { status: 'A' } })
C. db.collection.find({ $match: { status: 'A' } })
D. db.collection.aggregate([{ match: { status: 'A' } }])
Solution
Step 1: Identify correct aggregation syntax
The aggregate method takes an array of stages, each stage is an object with a stage operator like $match.
Step 2: Check each option
db.collection.aggregate([{ $match: { status: 'A' } }]) correctly uses an array with $match stage. db.collection.aggregate({ $match: { status: 'A' } }) misses array brackets. db.collection.find({ $match: { status: 'A' } }) uses find() which is not aggregation. db.collection.aggregate([{ match: { status: 'A' } }]) misses $ in $match.
Final Answer:
db.collection.aggregate([{ $match: { status: 'A' } }]) -> Option A