It looks like mongodb offers two similar functions for geospatial queries - $near
and $geoNear
. According to the mongo docs
The geoNear command provides an alternative to the $near operator. In addition to the functionality of $near, geoNear returns additional diagnostic information.
It looks like geoNear
provides a superset of the near
functionality. For example, near
seems to only return the closest 100 documents, whereas geoNear
lets you specify a maximum. Is there a reason to use near
instead of geoNear
? Is one more efficient than the other?
Efficiency should be identical for either.
geoNear
's major limitation is that as a command it can return a result set up to the maximum document size as all of the matched documents are returned in a single result document. It also requires that a distance field be added to each result document which may or may not be an issue depending on your usage.
$near
is a query operator so the results can be larger than a single document (they are still returned in a single response but not a single document). You can also set the maximum number of documents via the query's limit().
I tend to recommend that users stick with the $near
unless they need the diagnostics
(e.g., distance, or location matched) from the geonear
command.
These are major differences :-
$geoNear also gives you distance from the point but $near command doesn't.
$geoNear command requires that the collection have at most only one 2d index and/or only one 2dsphere index whereas geospatial query operators like $near and $geoWithin permit collections to have multiple geospatial indexes. This is because in $geoNear command there is no option to specify the field on which you want to search, where as in $near command you can specify the field name.
The main difference is that $near is a query operator, but $geoNear
is an aggregation stage. Both return documents in order of nearest to farthest from the given point.
What it means is that $near can be used in find() queries or in the $match
aggregation stage, but $geoNear
cannot. Instead $geoNear
must be used as a separate aggregation stage only.
The options each feature provides also differ. I invite you to review the details in the corresponding documentation sections:
$near documentation
$geoNear documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With