MongoDB — Aggregation Pipeline
Pipeline Concept
Documents pass through stages sequentially.
Common Stages
$match
{ $match: { status: "active" } }
$group
{ $group: { _id: "$category", total: { $sum: "$amount" } } }
$sort
{ $sort: { total: -1 } }
$project
{ $project: { name: 1, email: 1, _id: 0 } }
$limit and $skip
{ $skip: 10 }
{ $limit: 5 }
$unwind
{ $unwind: "$hobbies" }
Accumulators
| Accumulator | Description |
|---|---|
| $sum | Sum values |
| $avg | Average |
| $min | Minimum |
| $max | Maximum |
| $first | First element |
| $last | Last element |
Example Pipeline
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $unwind: "$items" },
{ $group: {
_id: "$userId",
totalSpent: { $sum: "$items.price" }
}},
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
]);
Mini Practice
- Build a pipeline
- Use multiple stages
- Calculate aggregates
- Unwind arrays
Up Next
Continue with Group — grouping documents.
Related Topics
Frequently Asked Questions about Aggregation Pipeline
What is Aggregation Pipeline in MongoDB?
Aggregation Pipeline is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Aggregation Pipeline?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Aggregation Pipeline.
Why is Aggregation Pipeline important in MongoDB?
Aggregation Pipeline is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.