MongoDB geospatial difference between $near and $w

2019-02-14 07:59发布

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?

1条回答
疯言疯语
2楼-- · 2019-02-14 08:25

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.

查看更多
登录 后发表回答