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 the geonear command or$geoNear aggregation stage insteadAlso check out the documentation for $near and $geoWithin.
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