This optimization allows for more opportunities for $sort + $limit Coalescence (page 448), such as with $sort + $skip + $limit sequences. See $sort + $limit Coalescence (page 448) for details on the coalescence and $sort + $skip + $limit Sequence (page 449) for an example. 

For aggregation operations on sharded collections (page 450), this optimization reduces the results returned from each shard. 

$redact + $match Sequence Optimization When possible, when the pipeline has the $redact stage immedi- ately followed by the $match stage, the aggregation can sometimes add a portion of the $match stage before the $redact stage. If the added $match stage is at the start of a pipeline, the aggregation can use an index as well as query the collection to limit the number of documents that enter the pipeline. See Pipeline Operators and Indexes (page 441) for more information. 

For example, if the pipeline consists of the following stages: 

{ $redact: { $cond: { if : { $eq: [ "$level", 5 ] }, then: "$$PRUNE", else : "$$DESCEND" } } }, { $match: { year: 2014, category: { $ne: "Z" } } } 

The optimizer can add the same $match stage before the $redact stage: 

{ $match: { year: 2014 } }, { $redact: { $cond: { if : { $eq: [ "$level", 5 ] }, then: "$$PRUNE", else : "$$DESCEND" } } }, { $match: { year: 2014, category: { $ne: "Z" } } } 

## Pipeline Coalescence Optimization 

When possible, the optimization phase coalesces a pipeline stage into its predecessor. Generally, coalescence occurs after any sequence reordering optimization. 

$sort + $limit Coalescence When a $sort immediately precedes a $limit , the optimizer can coalesce the $limit into the $sort . This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory $^{11}$. See sort-and-memory for more information. 

$limit + $limit Coalescence When a $limit immediately follows another $limit , the two stages can coalesce into a single $limit where the limit amount is the smaller of the two initial limit amounts. For example, a pipeline contains the following sequence: 

{ $limit: 100 }, { $limit: 10 } 

Then the second $limit stage can coalesce into the first $limit stage and result in a single $limit stage where the limit amount 10 is the minimum of the two initial limits 100 and 10 . 

{ $limit: 10 } 

$skip + $skip Coalescence When a $skip immediately follows another $skip , the two stages can coalesce into a single $skip where the skip amount is the sum of the two initial skip amounts. For example, a pipeline contains the following sequence: 

{ $skip: 5 }, { $skip: 2 } 

