- 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
$nearSphereusing spherical geometry.The
$nearSphereoperator queries for points defined by either GeoJSON objects or legacy coordinate pairs.The optional
$maxDistanceoperator limits a$nearSpherequery to return only those documents that fall within a maximum distance of a point. If you use$maxDistanceon GeoJSON points, the distance is measured in meters. If you use$maxDistanceon legacy coordinate pairs, the distance is measured in radians.The
$nearSphereoperator requires a geospatial index. The2dsphereand2dindexes both support$nearSpherewith both legacy coordinate pairs and GeoJSON points. Queries that use a2dindex 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: