-
Type:
Task
-
Resolution: Unresolved
-
Priority:
Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
Query Optimization
-
None
-
None
-
None
-
None
-
None
-
None
-
None
A trailing $match after $geoNear is currently not pushed down into the geo stage.
A $match after $geoNear stays in the pipeline as a separate DocumentSourceMatch stage. The pipeline optimizer (DocumentSourceMatch::optimizeAt) only seems to merge consecutive $match stages. It does not merge into a preceding $geoNear. The buildInnerQueryExecutorGeoNear path pops $geoNear from the pipeline front, leaving trailing stages intact.
The $match is then executed as a pipeline stage after DocumentSourceGeoNearCursor produces documents.
This could be optimized by pushing the trailing $match expression into the $geoNear stage.
For example, in the following query, the $match stage is not merged into the $geoNear stage.
const explain = coll.explain("executionStats").aggregate([ { $geoNear: { near: {type: "Point", coordinates: [0, 0]}, distanceField: "dist", }, }, {$match: {k: {$gte: 2}}}, ]);