Aggregation Pipelines
Create and manage MongoDB aggregation pipelines
Aggregation Pipelines
Build powerful data transformation and analysis pipelines with MongoDB's aggregation framework.
Overview
Aggregation pipelines process documents through a sequence of stages, transforming and analyzing data at each step.
Pipeline Stages
Common aggregation stages:
$match
Filter documents (like find queries):
{
"$match": {
"status": "active",
"age": { "$gte": 18 }
}
}
$group
Group documents and calculate aggregates:
{
"$group": {
"_id": "$category",
"total": { "$sum": "$amount" },
"count": { "$sum": 1 },
"average": { "$avg": "$rating" }
}
}
$project
Reshape documents and compute fields:
{
"$project": {
"name": 1,
"fullName": { "$concat": ["$firstName", " ", "$lastName"] },
"age": { "$subtract": [2024, "$birthYear"] }
}
}
$sort
Order documents:
{
"$sort": {
"createdAt": -1
}
}
$limit
Limit number of documents:
{
"$limit": 100
}
$lookup
Join collections:
{
"$lookup": {
"from": "orders",
"localField": "_id",
"foreignField": "userId",
"as": "userOrders"
}
}
Visual Pipeline Builder
TeamBuild pipelines visually:
Stage Preview
See intermediate results after each stage:
- Document count at each step
- Sample output documents
- Stage performance metrics
Preview results help you understand how each stage transforms your data.
Common Pipeline Patterns
Group and Count
Count documents by category:
[
{
"$group": {
"_id": "$category",
"count": { "$sum": 1 }
}
},
{
"$sort": { "count": -1 }
}
]
Top N Results
Find top 10 items by value:
[
{
"$sort": { "revenue": -1 }
},
{
"$limit": 10
}
]
Calculate Running Total
[
{
"$sort": { "date": 1 }
},
{
"$group": {
"_id": null,
"transactions": {
"$push": {
"date": "$date",
"amount": "$amount"
}
}
}
},
{
"$unwind": {
"path": "$transactions",
"includeArrayIndex": "index"
}
}
]
Saving Pipelines
Save pipelines for reuse:
- Build your pipeline
- Click Save Pipeline
- Name and describe the pipeline
- Access from Saved Pipelines sidebar
Pipeline Performance
Optimization Tips
- $match early - Filter documents before expensive operations
- $project early - Remove unneeded fields
- Use indexes - $match and $sort can use indexes
- Limit results - Add $limit when appropriate
Performance Metrics
View pipeline performance:
- Execution time per stage
- Documents processed per stage
- Index usage
- Memory consumption
Pipelines without early $match may scan entire collections. Always filter first when possible.