Expressions help you transform and calculate data inside a pipeline step by step. They let you change data as it moves through the pipeline.
Why expressions matter in pipelines in MongoDB
In a MongoDB aggregation pipeline stage, use expressions inside operators like $project, $match, $group, etc.
Example:
{
$project: {
newField: { $add: ["$field1", "$field2"] }
}
}Expressions are written as JSON objects starting with a $ operator.
They can be nested to perform complex calculations.
totalPrice by multiplying price and quantity.{ $project: { totalPrice: { $multiply: ["$price", "$quantity"] } } }score field is greater than 50 using an expression.{ $match: { $expr: { $gt: ["$score", 50] } } }category and calculates the average price in each group.{ $group: { _id: "$category", averagePrice: { $avg: "$price" } } }This pipeline calculates the total cost for each sale by multiplying price and quantity. Then it filters to keep only sales where total cost is more than 100.
db.sales.aggregate([
{
$project: {
item: 1,
totalCost: { $multiply: ["$price", "$quantity"] }
}
},
{
$match: {
$expr: { $gt: ["$totalCost", 100] }
}
}
])Expressions let you do math, string operations, date calculations, and more inside pipelines.
Using expressions makes pipelines flexible and powerful for data transformation.
Expressions let you calculate and transform data inside pipeline stages.
They are used in many stages like $project, $match, and $group.
Understanding expressions helps you write better and more useful pipelines.
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
