Why expressions matter in pipelines in MongoDB - Performance Analysis
When using MongoDB pipelines, the way expressions are written affects how long queries take to run.
We want to understand how the choice of expressions changes the work the database does as data grows.
Analyze the time complexity of the following MongoDB aggregation pipeline snippet.
db.orders.aggregate([
{ $match: { status: "A" } },
{ $project: {
totalPrice: { $multiply: ["$price", "$quantity"] },
discountPrice: { $subtract: ["$price", "$discount"] }
}
}
])
This pipeline filters orders with status "A" and calculates new fields using expressions.
Look for repeated work done on each document in the collection.
- Primary operation: Applying expressions ($multiply, $subtract) to each matched document.
- How many times: Once for every document that matches the filter.
As the number of matching documents grows, the database must do more calculations.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calculations |
| 100 | About 100 calculations |
| 1000 | About 1000 calculations |
Pattern observation: The work grows directly with the number of matching documents.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of documents processed.
[X] Wrong: "Expressions inside pipelines run once, so their cost does not grow with data size."
[OK] Correct: Each expression runs for every document that passes through, so more documents mean more work.
Understanding how expressions affect pipeline performance helps you write efficient queries and shows you think about real data growth.
What if we added a $group stage after $project that aggregates results? How would that change the time complexity?
Practice
Solution
Step 1: Understand the role of expressions in pipelines
Expressions let you perform calculations and data transformations inside stages like $project and $group.Step 2: Compare other options
Options A, B, and C describe unrelated features not handled by expressions.Final Answer:
They allow you to calculate and transform data within pipeline stages. -> Option DQuick Check:
Expressions = Data transformation [OK]
- Thinking expressions create collections
- Confusing expressions with indexing
- Assuming expressions handle backups
price and tax?Solution
Step 1: Identify correct expression syntax
The $add operator requires an array of field references with $ prefix inside an object.Step 2: Check each option
{ $project: { total: { $add: ["$price", "$tax"] } } } correctly uses $add with an array of "$price" and "$tax". Others misuse syntax or operators.Final Answer:
{ $project: { total: { $add: ["$price", "$tax"] } } } -> Option AQuick Check:
$add needs array with $field names [OK]
- Omitting $ before field names
- Using parentheses instead of array for $add
- Confusing $add with $sum operator
{ $project: { discountedPrice: { $multiply: ["$price", 0.9] } } } What will be the output for a document { price: 100 }?Solution
Step 1: Understand $multiply expression
$multiply multiplies the values in the array. Here, price (100) * 0.9 = 90.Step 2: Apply to given document
Input price is 100, so discountedPrice = 100 * 0.9 = 90.Final Answer:
{ discountedPrice: 90 } -> Option BQuick Check:
100 * 0.9 = 90 [OK]
- Confusing multiplication with subtraction
- Using 0.9 as a field instead of a number
- Expecting original price unchanged
{ $project: { total: { $add: "$price", "$tax" } } }Solution
Step 1: Review $add operator syntax
$add expects a single array argument containing expressions, not multiple separate arguments.Step 2: Analyze given code
The code passes "$price" and "$tax" as separate arguments instead of inside an array.Final Answer:
The $add operator requires an array of expressions, not separate arguments. -> Option CQuick Check:
$add needs array input [OK]
- Passing multiple arguments instead of array
- Removing $ from field names inside expressions
- Assuming $project can't use expressions
Solution
Step 1: Filter sales with $match before grouping
To include only sales with quantity > 5, $match must come before $group.Step 2: Use $avg with $multiply expression inside $group
Calculate revenue per sale as price * quantity, then average it per product.Step 3: Check options
{ $match: { quantity: { $gt: 5 } } }, { $group: { _id: "$product", avgRevenue: { $avg: { $multiply: ["$price", "$quantity"] } } } } correctly orders stages and uses expressions. Others have wrong order or wrong operators.Final Answer:
{ $match: { quantity: { $gt: 5 } } }, { $group: { _id: "$product", avgRevenue: { $avg: { $multiply: ["$price", "$quantity"] } } } } -> Option AQuick Check:
Filter then group with $avg of $multiply [OK]
- Placing $match after $group
- Using $sum instead of $avg for average
- Filtering with wrong comparison operator
Ready to prove it?
Pass the test and this pattern moves unknown
