What is the difference between $near
and $within
?
db.geodata.find({ "loc" : { "$within" : { "$center" : [ [ 12.91365 , 77.59395] , 4]}}}).limit(10);
db.geodata.find({ "loc" : { "$near" : [ 12.91365 , 77.59395] , "$maxDistance" : 4}}).limit(10);
Can anyone explain in detail?
The main differences are
$near
sorts based on distance from a point;$geoWithin
tests for containment in a polygon or multipolygon with GeoJSON coordinates, or containment in one of a set of shapes for 2d coordinates$near
returns document from nearest to farthest and any other order requires in-memory sorting;$geoWithin
can be used with other sort indexes$near
requires a geospatial index;$geoWithin
performs better with one but does not require it$near
is not supported in sharded clusters - you have to use thegeonear
command or$geoNear
aggregation stage insteadAlso check out the documentation for $near and $geoWithin.