|
$geoNear sorts documents by their distance from a given query point. But its implementation is very tied to a particular index-scan plan, so it can only appear as the first stage in a pipeline.
We can lift this restriction by splitting it up into separate stages. Using the new internal-only stage from SERVER-58745, we could rewrite it like this:
{$geoNear: {
|
key: <fieldname>,
|
near: <point>,
|
minDistance: <min>,
|
maxDistance: <max>,
|
}}
|
|
=>
|
|
{$match: { <fieldname>: {$geoWithin: {$centerSphere: [<point>, <max>]}} }}
|
{$match: { <fieldname>: {$not: {$geoWithin: {$centerSphere: [<point>, <min>]}}} }}
|
{$_internalGeoNearDistance: {
|
key: <fieldname>,
|
near: <point>,
|
}}
|
{$sort: {$meta: 'geoNearDistance'}}
|
Splitting it up this way will allow other rewrites to optimize the $geoWithin and $sort.
|