- Aggregation >
- Aggregation Concepts >
- Aggregation Mechanics >
- Aggregation Pipeline Optimization
Aggregation Pipeline Optimization¶
On this page
Changed in version 2.4.
Aggregation pipeline operations have an optimization phase which attempts to rearrange the pipeline for improved performance.
Pipeline Sequence Optimization¶
$sort + $skip + $limit Sequence Optimization¶
When you have a sequence with $sort followed by a
$skip followed by a $limit, an
optimization occurs that moves the $limit operator before
the $skip operator. For example, if the pipeline consists of
the following stages:
During the optimization phase, the optimizer transforms the sequence to the following:
The optimized sequence now has $sort immediately preceding
the $limit. See $sort for information on the
behavior of the $sort operation when it immediately
precedes $limit.
$limit + $skip + $limit + $skip Sequence Optimization¶
When you have a continuous sequence of a $limit pipeline
stage followed by a $skip pipeline stage, the optimization
phase attempts to arrange the pipeline stages to combine the limits
and skips. For example, if the pipeline consists of the following
stages:
During the intermediate step, the optimizer reverses the position of
the $skip followed by a $limit to
$limit followed by the $skip.
The $limit value has increased to the sum of the
initial value and the $skip value. Then, for the final
$limit value, the optimizer selects the minimum between
the adjacent $limit values. For the final
$skip value, the optimizer adds the adjacent
$skip values, to transform the sequence to the
following:
Projection Optimization¶
The aggregation pipeline can determine if it requires only a subset of the fields in the documents to obtain the results. If so, the pipeline will only use those required fields, reducing the amount of data passing through the pipeline.