OPTIONS

$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. The 2dsphere and 2d indexes both support $nearSphere with both legacy coordinate pairs and GeoJSON points. Queries that use a 2d index return a at most 100 documents.

Important

If you use longitude and latitude, specify longitude first.

For queries on GeoJSON data, use the following syntax:

db.<collection>.find( { <location field> :
                         { $nearSphere :
                           { $geometry :
                              { type : "Point" ,
                                coordinates : [ <longitude> , <latitude> ] } ,
                             $maxDistance : <distance in meters>
                   } } } )

For queries on legacy coordinate pairs, use the following syntax:

db.<collection>.find( { <location field> :
                         { $nearSphere: [ <x> , <y> ] ,
                           $maxDistance: <distance in radians>
                      } } )

The following example selects the 100 documents with legacy coordinates pairs nearest to [ 40 , 5 ], as calculated by spherical geometry:

db.places.find( { loc :
                   { $nearSphere : [ 40 , 5 ] ,
                     $maxDistance : 10
                } } )
←   $near $geometry  →
ON THIS PAGE