- Reference >
- Operators >
- Query and Projection Operators >
- Geospatial Query Operators >
- $nearSphere
$nearSphere¶
-
$nearSphere
¶ New in version 1.8.
Specifies a point for which a geospatial query returns the closest documents first. The query sorts the documents from nearest to farthest. MongoDB calculates distances for
$nearSphere
using spherical geometry.The
$nearSphere
operator queries for points defined by either GeoJSON objects or legacy coordinate pairs.The optional
$maxDistance
operator limits a$nearSphere
query to return only those documents that fall within a maximum distance of a point. If you use$maxDistance
on GeoJSON points, the distance is measured in meters. If you use$maxDistance
on legacy coordinate pairs, the distance is measured in radians.The
$nearSphere
operator requires a geospatial index. The2dsphere
and2d
indexes both support$nearSphere
with both legacy coordinate pairs and GeoJSON points. Queries that use a2d
index return at most 100 documents.Important
If you use longitude and latitude, specify longitude first.
For queries on GeoJSON data, use the following syntax:
For queries on legacy coordinate pairs, use the following syntax:
The following example selects the 100 documents with legacy coordinates pairs nearest to
[ 40 , 5 ]
, as calculated by spherical geometry: