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:

JavaScript
{
    _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:

JavaScript
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.

JavaScript
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:

JavaScript
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:

JavaScript
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:

JavaScript
{
    _id: 1001,
    customerId: 101,
    totalAmount: 2500,
    status: "Completed"
}

The customers collection contains:

JavaScript
{
    _id: 101,
    customerName: "Rahul Sharma",
    city: "Patna"
}

The application can use $lookup to retrieve customer information for each order.

JavaScript
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:

JavaScript
db.customers.createIndex({
    email: 1
});

A lookup using email can then benefit from the supporting index:

JavaScript
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:

JavaScript
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:

JavaScript
{
    transactionId: 5001,
    accountId: 101,
    category: "Transfer",
    amount: 2500,
    transactionDate: ISODate("2026-11-24T10:00:00Z")
}

The following aggregation calculates transaction totals by account:

JavaScript
db.transactions.aggregate([
    {
        $group: {
            _id: "$accountId",
            totalAmount: {
                $sum: "$amount"
            },
            transactionCount: {
                $sum: 1
            }
        }
    }
]);

If the collection contains millions of transactions and thousands of accounts, MongoDB must process the input records and maintain aggregate information for the groups.

The stage can become expensive when the pipeline processes too many input documents or produces a large number of groups.

Start by examining the number of documents entering the grouping operation. If the application only needs transactions from a particular month, filter by date before grouping.

JavaScript
db.transactions.aggregate([
    {
        $match: {
            transactionDate: {
                $gte: ISODate("2026-11-01T00:00:00Z"),
                $lt: ISODate("2026-12-01T00:00:00Z")
            }
        }
    },
    {
        $group: {
            _id: "$accountId",
            totalAmount: {
                $sum: "$amount"
            },
            transactionCount: {
                $sum: 1
            }
        }
    }
]);

This limits the number of records that need to be processed.

MongoDB can use indexes for an initial $match, allowing it to reduce the input before the aggregation framework performs the grouping operation.

Also examine the number of unique grouping keys. Grouping by accountId generally produces fewer groups than grouping by a unique transactionId.

The number of groups matters because each group requires aggregation state.

Starting with MongoDB 5.2, certain $group operations can use the slot-based execution engine when the required conditions are met. In explain output, this can appear as a GROUP execution stage.

The execution engine can improve performance, but it does not eliminate the need to reduce unnecessary input data.

Finding Expensive $sort Stages

Sorting large datasets can consume considerable memory.

Consider a reporting pipeline that calculates revenue by category and sorts the results:

JavaScript
db.orders.aggregate([
    {
        $group: {
            _id: "$category",
            totalRevenue: {
                $sum: "$totalAmount"
            }
        }
    },
    {
        $sort: {
            totalRevenue: -1
        }
    }
]);

The sort operation cannot generally use an ordinary collection index to sort the calculated totalRevenue values because those values are produced by the preceding $group stage.

MongoDB must sort the resulting grouped documents.

If the pipeline produces many groups, this operation can require significant memory. Depending on the operation and server configuration, the stage may spill data to disk.

Explain output can include fields such as usedDisk, spills, spilledRecords, spilledDataStorageSize, and peakTrackedMemBytes for supported stages and execution modes.

These fields help identify whether sorting is creating additional disk activity.

If the application only needs the top ten categories, use $limit after sorting:

JavaScript
db.orders.aggregate([
    {
        $group: {
            _id: "$category",
            totalRevenue: {
                $sum: "$totalAmount"
            }
        }
    },
    {
        $sort: {
            totalRevenue: -1
        }
    },
    {
        $limit: 10
    }
]);

MongoDB can optimize a $sort followed by a $limit by maintaining only the top required results where the optimization applies.

This can reduce memory requirements compared with sorting and retaining every result.

However, adding a limit changes the result set. Use it only when the application genuinely needs a limited number of results.

Understanding Disk Spills and Memory Usage

Some aggregation stages need to maintain intermediate data while processing documents.

For example, $group and $sort may need memory to store group information or sorting buffers.

MongoDB applies memory limits to aggregation stages. When an eligible stage exceeds its available memory, it may write temporary data to disk if disk use is permitted.

In MongoDB versions that support the allowDiskUseByDefault setting, the server configuration determines the default behavior for eligible operations. An individual aggregation can also specify allowDiskUse.

For example:

JavaScript
db.orders.aggregate(
    [
        {
            $match: {
                status: "Completed"
            }
        },
        {
            $group: {
                _id: "$category",
                totalRevenue: {
                    $sum: "$totalAmount"
                }
            }
        },
        {
            $sort: {
                totalRevenue: -1
            }
        }
    ],
    {
        allowDiskUse: true
    }
);

Allowing disk use can prevent an eligible aggregation from failing because of its memory limit. However, it does not make an inefficient pipeline efficient.

Disk spills introduce additional I/O and can increase execution time. If an aggregation repeatedly spills large amounts of data, investigate whether it can process fewer documents, create fewer groups, or use a different data model.

Also check whether the explain output reports actual spill information. Do not assume that a stage used disk simply because allowDiskUse is enabled.

Understanding MongoDB Pipeline Optimization

MongoDB includes an aggregation pipeline optimizer that can reshape pipelines before execution.

This is important because the execution plan may not look exactly like the pipeline written by the developer.

For example, consider:

JavaScript
db.orders.aggregate([
    {
        $match: {
            status: "Completed"
        }
    },
    {
        $sort: {
            orderDate: -1
        }
    },
    {
        $limit: 20
    }
]);

MongoDB may push eligible operations into the initial query execution plan. If an index supports the filter and sort pattern, the database can avoid processing unnecessary records.

MongoDB can also coalesce certain stages. For example, an immediately following $unwind on a $lookup result can be absorbed into the lookup operation. A subsequent $match on the joined array fields can sometimes be incorporated as well.

This reduces the number of large intermediate documents created between stages.

A practical example is:

JavaScript
db.orders.aggregate([
    {
        $lookup: {
            from: "customers",
            localField: "customerId",
            foreignField: "_id",
            as: "customerDetails"
        }
    },
    {
        $unwind: "$customerDetails"
    },
    {
        $match: {
            "customerDetails.city": "Patna"
        }
    }
]);

MongoDB can optimize eligible lookup, unwind, and match combinations rather than always materializing the entire joined array before applying the filter.

Always inspect explain output to understand which optimizations were applied. Optimizer behavior can change between MongoDB releases, so avoid relying on a particular internal plan shape without testing the version used in production.

Reading Explain Output for Aggregation Stages

When investigating an expensive pipeline, focus on the following areas.

Explain information What it helps identify
COLLSCAN Collection scans caused by missing or unsuitable indexes
IXSCAN Index access used by the query plan
totalDocsExamined Number of documents examined
totalKeysExamined Number of index keys examined
nReturned Number of documents returned
indexesUsed Indexes used by supported lookup execution details
usedDisk Whether a supported stage used disk
spills Spill activity reported for supported stages
peakTrackedMemBytes Peak tracked memory for supported stages

Do not judge performance using only executionTimeMillis.

For example, a query that returns 100 documents after examining 10 million documents may be inefficient even if it finishes quickly on a lightly loaded development server.

Likewise, a pipeline that returns a large number of documents may legitimately examine many records. The ratio between documents examined and documents returned is a useful diagnostic clue, but it is not a universal performance threshold.

For aggregations, also compare the number of documents entering and leaving expensive stages whenever the explain output provides enough information to do so.

Monitoring Slow Aggregations in Production

Running explain() on every aggregation in production is not practical. Developers need a way to identify which operations deserve investigation.

MongoDB provides several monitoring options.

Atlas Query Profiler

For MongoDB Atlas deployments, the Query Profiler helps identify slow operations and performance outliers.

It can help developers find query patterns that consistently consume more resources or have unusually high latency.

Database Profiler

Self-managed MongoDB deployments can use the database profiler to capture operation information in the system.profile collection.

For example, the following command enables profiling for slow operations:

JavaScript
db.setProfilingLevel(
    1,
    {
        slowms: 100
    }
);

This example records operations that exceed the configured slow-operation threshold.

The threshold should be selected according to application requirements. A query taking 100 milliseconds may be acceptable for a background report but unacceptable for a frequently executed API request.

The database profiler can affect server performance and consume disk space. It may also store query metadata, so consider operational and security implications before enabling it.

For production monitoring, use the profiler selectively and disable or adjust it when the investigation is complete.

Diagnostic Logs

MongoDB diagnostic logs can also provide information about slow operations.

They are useful when an application experiences intermittent performance problems and developers need to correlate database activity with application logs, deployment events, or traffic spikes.

The key is to identify recurring query shapes rather than investigating every individual execution separately.

A Practical Workflow for Finding Expensive Stages

When an aggregation becomes slow, follow a structured investigation instead of changing several stages at once.

  1. Reproduce the aggregation with representative production-like data.
  2. Run explain with executionStats to inspect the winning plan and execution metrics.
  3. Check the initial data-access stage for collection scans and excessive documents examined.
  4. Examine $lookup operations for missing foreign-field indexes and unnecessarily large input sets.
  5. Inspect $group operations for excessive input documents or a large number of distinct grouping keys.
  6. Review $sort operations for memory consumption and disk spills.
  7. Check whether MongoDB already applies pipeline optimizations.
  8. Change one part of the pipeline or its indexing strategy at a time.
  9. Run explain again and compare the results.
  10. Validate that the optimized pipeline returns the same business results.

This approach makes it easier to identify which change actually improves performance.

It also reduces the risk of introducing a faster pipeline that produces incorrect business results.

Conclusion

MongoDB aggregation pipelines can become expensive when they process large datasets, perform inefficient joins, maintain too many groups, or sort more records than necessary.

The explain() method provides the information needed to investigate these problems. By examining document scans, index usage, execution statistics, lookup details, memory consumption, and disk spills, developers can identify which operations are responsible for unnecessary work.

The most effective optimizations usually begin with reducing the number of documents entering the pipeline, supporting lookup operations with appropriate indexes, limiting unnecessary grouping and sorting, and understanding the transformations performed by MongoDB's pipeline optimizer.

For production applications, combine explain-based analysis with query profiling and diagnostic logs. This provides a repeatable way to identify expensive aggregation stages, measure improvements, and keep database performance predictable as the application grows.