Aggregation Overview
MongoDB’s aggregation framework performs complex transformations and analysis on documents by building data processing pipelines.
Aggregation Pipeline Stages
- $match: Filters documents matching criteria
- $group: Groups documents based on specified fields
- $project: Selects or renames output fields
- $sort: Sorts results
- $limit: Limits output document count
- $skip: Skips documents
Common Operations Explained
$match Filter
db.users.aggregate([
{
$match: {
age: { $gt: 18 },
status: "active"
}
}
])
$group Grouping
db.orders.aggregate([
{ $match: { status: "completed" } },
{
$group: {
_id: "$customer_id",
total: { $sum: "$amount" },
avg: { $avg: "$amount" }
}
}
])
$project Projection
db.orders.aggregate([
{
$project: {
customer: 1,
total: { $multiply: ["$price", "$quantity"] },
_id: 0
}
}
])
$sort Sorting
db.employees.aggregate([
{
$sort: {
department: 1,
salary: -1
}
}
])
Performance Optimization Suggestions
- Try to use
$matchat the pipeline front to reduce number of documents processed - Use indexes reasonably to accelerate aggregation queries
- Avoid processing large amounts of data in
$groupstage - Consider using allowDiskOption option for large datasets