Optimizing aggregation pipelines
When we submit the aggregation pipeline for execution, MongoDB might reorder and group execution stages to improve performance.
We can inspect these optimizations by including the explain
option in the aggregation execution command in the shell or our programming language’s driver.
Further to the optimizations that MongoDB will perform independently, we should aim to design our aggregation commands with an eye on limiting the number of documents that need to pass from one stage to the next, as early as possible.
This can be done in two ways.
The first way is by using indexes to improve the querying speed in every step of the aggregation pipeline. The rules are as follows:
- The planner will use an index in a
$match
stage if$match
is the first stage in the pipeline. The planner will use an index in the$sort
stage if$sort
is not preceded by a$group
,$project
, or$unwind
stage. - The planner might use an index in the
$group...