MongoDB — Aggregation
Basic Aggregation
db.users.aggregate([
{ $match: { active: true } },
{ $group: { _id: "$country", count: { $sum: 1 } } }
])
Pipeline Stages
| Stage | Description |
|---|---|
| $match | Filter documents |
| $group | Group documents |
| $sort | Sort documents |
| $project | Reshape documents |
| $limit | Limit results |
| $skip | Skip documents |
| $lookup | Join collections |
| $unwind | Deconstruct arrays |
Examples
// Group by country
db.users.aggregate([
{ $group: { _id: "$country", count: { $sum: 1 } } }
])
// Average age by country
db.users.aggregate([
{ $group: { _id: "$country", avgAge: { $avg: "$age" } } }
])
// Sort by count
db.users.aggregate([
{ $group: { _id: "$country", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
Lookup (Join)
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
}
])
Mini Practice
- Use $match and $group
- Calculate aggregates
- Sort results
- Use $lookup
Up Next
Continue with Aggregation Pipeline — pipeline details.
Related Topics
Frequently Asked Questions about Aggregation
What is Aggregation in MongoDB?
Aggregation 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?
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.
Why is Aggregation important in MongoDB?
Aggregation is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.