$near
Returns documents whose location field is near a specified point, sorted by distance, requiring a 2dsphere index and returning documents from nearest to farthest.
Syntax
{ <location field>: { $near: { $geometry: { type: "Point", coordinates: [<longitude>, <latitude>] }, $maxDistance: <distance>, $minDistance: <distance> } } }
Parameters
location field
stringrequiredThe field containing the GeoJSON Point
geometry
objectrequiredGeoJSON Point object specifying the center point
maxDistance
numberOptional maximum distance in meters from the center point
minDistance
numberOptional minimum distance in meters from the center point
Examples
Basic proximity search
Find the closest stores to a specific geographic point
Query:
db.stores.find({ location: { $near: { $geometry: { type: "Point", coordinates: [69.7296, 70.1272] } } } })
Output:
Stores ordered by distance from the specified point, nearest first
Proximity search with distance range
Find stores within a specific distance range using aggregation
Query:
db.stores.aggregate([{ $geoNear: { near: { type: "Point", coordinates: [70.3328, 69.2158] }, distanceField: "distance", minDistance: 20, maxDistance: 200 } }])
Output:
Stores between 20 and 200 meters from the point with distance information