Expressions help you transform and calculate data inside a pipeline step by step. They let you change data as it moves through the pipeline.
0
0
Why expressions matter in pipelines in MongoDB
Introduction
When you want to add new fields based on existing data.
When you need to filter documents using calculated values.
When you want to group data and perform calculations like sums or averages.
When you want to reshape data by combining or splitting fields.
When you want to sort or limit data based on computed results.
Syntax
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.
Examples
This creates a new field
totalPrice by multiplying price and quantity.MongoDB
{ $project: { totalPrice: { $multiply: ["$price", "$quantity"] } } }This filters documents where the
score field is greater than 50 using an expression.MongoDB
{ $match: { $expr: { $gt: ["$score", 50] } } }This groups documents by
category and calculates the average price in each group.MongoDB
{ $group: { _id: "$category", averagePrice: { $avg: "$price" } } }Sample Program
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.
MongoDB
db.sales.aggregate([
{
$project: {
item: 1,
totalCost: { $multiply: ["$price", "$quantity"] }
}
},
{
$match: {
$expr: { $gt: ["$totalCost", 100] }
}
}
])OutputSuccess
Important Notes
Expressions let you do math, string operations, date calculations, and more inside pipelines.
Using expressions makes pipelines flexible and powerful for data transformation.
Summary
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.