Process data through a sequence of stages. Each stage transforms the document stream.
| Stage | Description |
|---|---|
$match | Filter documents using query operators |
$group | Group by key with accumulators ($sum, $avg, $min, $max, $count, $first, $last, $push) |
$sort | Sort documents (1 asc, -1 desc) |
$project | Include/exclude fields, compute new fields |
$limit | Limit output count |
$skip | Skip N documents |
$unwind | Deconstruct array field into separate documents |
$addFields | Add computed fields |
$lookup | Join with another collection |
$count | Count documents and output as named field |
[
{"$group": {
"_id": "$department",
"avg_salary": {"$avg": "$salary"},
"total": {"$sum": 1},
"max_age": {"$max": "$age"},
"names": {"$push": "$name"}
}},
{"$sort": {"avg_salary": -1}},
{"$limit": 5}
]
{
"$lookup": {
"from": "orders",
"local_field": "_id",
"foreign_field": "user_id",
"as": "user_orders"
}
}
Use inside $project and $addFields:
{"$addFields": {
"total": {"$add": ["$price", "$tax"]},
"discount_price": {"$multiply": ["$price", 0.9]}
}}
Available: $add, $subtract, $multiply, $divide