$nearSphere

Returns documents with location fields near a specified point on a sphere, calculating distances using spherical geometry, more accurate for Earth-based calculations than $near.

Syntax

{ <location field>: { $nearSphere: { $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 on a spherical surface

minDistancenumber

Optional minimum distance in meters on a spherical surface

Examples

Basic spherical search

Find stores closest to a point using spherical Earth calculations

Query:

db.stores.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [-141.9922, 16.8331] } } } })

Output:

Stores ordered by spherical distance from the specified point

Spherical search with distance range

Find stores within specific distance range using spherical geometry

Query:

db.stores.aggregate([{ $geoNear: { near: { type: "Point", coordinates: [65.3765, -44.8674] }, distanceField: "sphericalDistance", minDistance: 20, maxDistance: 200, spherical: true } }])

Output:

Stores between 20-200 meters using accurate spherical distance calculations

Near sphere with field projection

Find nearest stores using spherical geometry and return specific fields

Query:

db.stores.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [-141.9922, 16.8331] } } } }, { name: 1, location: 1 })

Output:

Name and location of stores ordered by spherical proximity

Related