$maxDistance

Specifies the maximum distance (in meters) that can exist between two points in a geospatial query, typically used with $near for radius-based location searches.

Syntax

{ <location field>: { $near: { $geometry: { type: "Point", coordinates: [<longitude>, <latitude>] }, $maxDistance: <distance_in_meters> } } }

Parameters

location fieldstringrequired

The field containing the geospatial data

coordinatesobjectrequired

Array of [longitude, latitude] specifying the center point

distance_in_metersnumberrequired

Maximum distance in meters from the center point

Examples

Find stores within maximum distance

Find stores within 10 kilometers of a specific location

Query:

db.stores.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-77.9951, -62.7339] }, $maxDistance: 10000 } } })

Output:

Stores within 10000 meters (10km) of the specified coordinates

Distance-limited search with projection

Find nearby stores within distance limit and return specific fields

Query:

db.stores.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-77.9951, -62.7339] }, $maxDistance: 5000 } } }, { name: 1, location: 1 })

Output:

Name and location of stores within 5000 meters of the center point

Related