An aggregation pipeline using $match should be optimized so that the $match is moved as close as possible to the front of the pipeline, reducing the number of documents passing through each subsequent stage.
Work is planned for the following optimizations, and is tracked in these tickets:
- $match and $unwind:
- $match and $lookup:
- $match and $geoNear: SERVER-23466
- $match and $project:
This is an optimization we can apply in the future.
Applying matches before other operations allows less work to be done in the pipeline because documents will have been filtered out.
Matches can't be pushed earlier than just anything. For example, a $match can't be pushed ahead of a $skip or $limit, because it will change the results. On the other hand, a $match can be pushed ahead of a $project when it doesn't depend on a computed value in the project – field renames don't alter anything except the references in the $match.
Being able to push matches earlier will allow us to use indexes for the underlying query.