A MongoDB aggregation pipeline can look simple in application code but become expensive when it processes millions of documents. A dashboard might combine customer records with orders, calculate monthly revenue, group transactions by category, and sort the results before returning them to the application.
The pipeline may work correctly with a small development database. However, as the production dataset grows, response times can increase significantly. The application might start consuming more CPU and memory, aggregation stages may spill data to disk, and database resources may become unavailable for other operations.
The difficult part is identifying which stage is responsible.
An aggregation pipeline executes a sequence of operations, and each stage receives documents from the previous stage. If an early stage passes too many documents forward, later stages may perform unnecessary work. A large $lookup can retrieve excessive related data, a $group can maintain too many groups in memory, and a $sort can become expensive when MongoDB cannot use an appropriate index.
MongoDB provides explain() to inspect aggregation execution plans and execution statistics. Developers can use this information to identify expensive stages, understand how much data is being examined, and determine where an optimization will have the greatest impact.
This article explains how to investigate aggregation performance, interpret explain output, identify expensive $match, $lookup, $group, and $sort stages, and improve pipelines without changing their intended results.
Understanding How an Aggregation Pipeline Executes
An aggregation pipeline consists of multiple stages. Each stage receives documents from the previous stage, performs an operation, and passes the resulting documents to the next stage.
Consider an application that stores customer orders:
{
_id: ObjectId("674100000000000000000001"),
customerId: 101,
orderDate: ISODate("2026-11-20T10:00:00Z"),
status: "Completed",
totalAmount: 2500,
category: "Electronics"
}
The application needs to calculate total revenue by category for completed orders.
A simple aggregation might look like this:
db.orders.aggregate([
{
$match: {
status: "Completed"
}
},
{
$group: {
_id: "$category",
totalRevenue: {
$sum: "$totalAmount"
},
totalOrders: {
$sum: 1
}
}
},
{
$sort: {
totalRevenue: -1
}
}
]);
The pipeline has three stages:
- $match filters completed orders.
- $group calculates revenue and order counts for each category.
- $sort arranges categories by revenue.
The pipeline is straightforward, but its performance depends on several factors.
If the orders collection contains millions of records and status is not indexed, the first stage may scan the entire collection. If the application has thousands of categories, the grouping stage may maintain a large number of groups. If the result contains many groups, the final sorting operation may also require significant resources.
Understanding the amount of work performed at each stage is more useful than simply looking at the total execution time.
Using explain() to Investigate an Aggregation
MongoDB provides explain() for examining query plans and aggregation execution statistics.
For an aggregation pipeline, use executionStats to execute the operation and return information about the winning plan.
db.orders.explain("executionStats").aggregate([
{
$match: {
status: "Completed"
}
},
{
$group: {
_id: "$category",
totalRevenue: {
$sum: "$totalAmount"
},
totalOrders: {
$sum: 1
}
}
},
{
$sort: {
totalRevenue: -1
}
}
]);
The executionStats verbosity mode provides information about the selected plan and how it performed.
Important fields include:
- executionTimeMillis: The time reported for the operation during explain execution.
- totalDocsExamined: The number of documents examined.
- totalKeysExamined: The number of index keys examined.
- nReturned: The number of documents returned by the operation.
- executionStages: Information about the execution stages when available.
- usedDisk: Whether a stage used disk for processing, when reported.
- spills: Information about data spilling to disk, when reported.
For aggregation pipelines, the explain output often contains a top-level stages array. The first entry is normally $cursor, which contains information about the data-access portion of the pipeline. Other entries describe aggregation framework stages.
However, do not assume that the explain output always has exactly the same structure as the pipeline you wrote. MongoDB can move or combine stages during optimization. Some operations may be absorbed into the query execution plan rather than appearing as separate aggregation stages.
For example, an initial $match may appear as a filter inside the $cursor plan. A $group or $lookup may also be represented as a query execution stage when MongoDB can use an optimized execution path.
The actual explain structure depends on the pipeline, server version, and execution engine.
Identifying Collection Scans and Inefficient Filters
One of the first things to investigate is whether MongoDB is scanning an entire collection before processing the aggregation.
Consider this pipeline:
db.orders.aggregate([
{
$match: {
customerId: 101,
status: "Completed"
}
},
{
$group: {
_id: "$category",
totalRevenue: {
$sum: "$totalAmount"
}
}
}
]);
If the collection does not have an appropriate index, MongoDB may examine a large number of documents to find orders for customer 101.
Run the explain operation and inspect the winning plan.
A COLLSCAN stage indicates that MongoDB is scanning collection documents. An IXSCAN stage indicates that an index is being scanned.
For a query that filters by customerId and status, a compound index may be appropriate:
db.orders.createIndex({
customerId: 1,
status: 1
});
The index order should be selected based on the application's broader query patterns, including equality conditions, range filters, and sorting requirements.
After creating the index, run explain() again and compare the execution statistics.
Pay particular attention to the number of documents examined and the number of index keys examined.
A query that returns 20 documents after examining several million documents deserves investigation. However, a collection scan is not automatically a performance problem. It can be reasonable when a collection is small or when the aggregation needs to process most of its documents.
The important question is whether the selected access path performs unnecessary work for the actual workload.
Finding Expensive $lookup Stages
The $lookup stage combines documents from one collection with matching documents from another collection.
For example, an application might store orders and customers separately.
The orders collection contains:
{
_id: 1001,
customerId: 101,
totalAmount: 2500,
status: "Completed"
}
The customers collection contains:
{
_id: 101,
customerName: "Rahul Sharma",
city: "Patna"
}
The application can use $lookup to retrieve customer information for each order.
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
]);
A common performance issue occurs when MongoDB must perform expensive matching against the foreign collection.
For an equality lookup, the foreignField should generally have a supporting index. In this example, customers._id already has the default unique index created for the collection.
For a lookup using another field, create an appropriate index on the foreign collection.
For example:
db.customers.createIndex({
email: 1
});
A lookup using email can then benefit from the supporting index:
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerEmail",
foreignField: "email",
as: "customerDetails"
}
}
]);
When inspecting explain output, look for the $lookup execution information. Depending on the server version and execution engine, the output can include:
- totalDocsExamined
- totalKeysExamined
- collectionScans
- indexesUsed
- executionTimeMillisEstimate
These fields help determine whether the foreign collection is being accessed efficiently.
Another important optimization is to reduce the number of documents entering the $lookup stage.
For example, instead of joining every order and filtering afterward, filter the required orders first:
db.orders.aggregate([
{
$match: {
status: "Completed",
orderDate: {
$gte: ISODate("2026-11-01T00:00:00Z"),
$lt: ISODate("2026-12-01T00:00:00Z")
}
}
},
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
]);
This reduces the number of documents passed to the join operation.
When a pipeline contains a large number of correlated lookups, also review the data model. If an application repeatedly retrieves the same customer information for every order, embedding selected customer fields or maintaining a suitable read model may be more efficient than repeatedly joining collections.
Investigating Expensive $group Stages
The $group stage combines documents based on a grouping key and calculates aggregate values.
It is commonly used for reports, analytics, financial summaries, and dashboard calculations.
Consider a collection containing millions of transactions:
{
transactionId: 5001,
accountId: 101,
category: "Transfer",
amount: 2500,
transactionDate: ISODate("2026-11-24T10:00:00Z")
}
Join the conversation! Your thoughts help the community grow.