$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 fieldstringrequired

The field containing the GeoJSON Point

geometryobjectrequired

GeoJSON Point object specifying the center point

maxDistancenumber

Optional maximum distance in meters from the center point

minDistancenumber

Optional 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

Near query with field projection

Find nearest stores and return only specific fields

Query:

db.stores.find({ location: { $near: { $geometry: { type: "Point", coordinates: [69.7296, 70.1272] } } } }, { name: 1, location: 1 })

Output:

Name and location of stores ordered by proximity to the point

Related