To perform complex data processing, transformation, and analysis directly within MongoDB using pipelines.
- When simple
find()queries are insufficient. - For grouping, summing, or averaging data (analytics).
- For joining collections (
$lookup).
An aggregation pipeline is an array of stages. Documents pass through stages in order.
db.collection.aggregate([
{ $stage1: { ... } },
{ $stage2: { ... } }
])Always place this first to reduce dataset size early.
{ $match: { status: "completed" } }Calculate metrics.
{
$group: {
_id: "$customerId", // Group by customer
totalSpent: { $sum: "$amount" },
averageOrder: { $avg: "$amount" }
}
}Left outer join with another collection.
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userDetails"
}
}Shape the output.
{
$project: {
name: 1,
totalSpent: 1,
_id: 0
}
}- Ensure the first
$matchstage hits an index. - Use
$limitand$skipfor pagination.
- Memory Limit: Each stage has a 100MB RAM limit. Use
{ allowDiskUse: true }for large operations, though it is slower. - Complexity: Debugging long pipelines is difficult; build them stage by stage.
Transformed and aggregated data returned efficiently without pulling all raw documents into the application layer.