Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB geospatial difference between $near and $within

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?

like image 400
Syed Abdul Kather Avatar asked Feb 11 '15 17:02

Syed Abdul Kather


1 Answers

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 the geonear command or$geoNear aggregation stage instead

Also check out the documentation for $near and $geoWithin.

like image 141
wdberkeley Avatar answered Nov 15 '22 00:11

wdberkeley