3. Pipeline Syntax, Stage Order, and Execution
Basic syntax
db.collection.aggregate([stage1, stage2, stage3])
A pipeline is an ordered array of stages. A stage consumes the current pipeline documents and produces documents for the next stage. Moving $match before or after $group can change the meaning: before grouping it filters source records; after grouping it filters summaries.
If $project removes a field, later stages cannot use the removed field unless it is recreated. Use explain() to investigate the execution plan and statistics for important pipelines.
Track the current document shape
Before adding a stage, identify which fields exist after the preceding stage. This prevents field-path errors.
Code Example
db.orders.aggregate([
{
$set: {
subtotal: {
$sum: {
$map: {
input: "$items",
as: "item",
in: { $multiply: ["$$item.quantity", "$$item.price"] }
}
}
}
}
},
{ $match: { subtotal: { $gt: 5000 } } }
]);Key Takeaways
- Pipeline order affects semantics.
- A stage's output is the next stage's input.
- Use explain output to investigate execution.
Knowledge Check
Can a later stage use a field removed by an earlier $project?