Calculate Distance Using Spherical Geometry

Warning

For spherical queries, use the 2dsphere index result.

The use of 2d index for spherical queries may lead to incorrectresults, such as the use of the 2d index for spherical queriesthat wrap around the poles.

The 2d index supports queries that calculate distances on aEuclidean plane (flat surface). The index also supports the followingquery operators and command that calculate distances using sphericalgeometry:

Note

While basic queries using spherical distance are supported bythe 2d index, consider moving to a 2dsphere index if yourdata is primarily longitude and latitude.

Important

The aforementioned operations use radians for distance. Otherspherical query operators do not, such as $geoWithin.

For spherical query operators to function properly, you must convertdistances to radians, and convert from radians to the distances unitsused by your application.

To convert:

  • distance to radians: divide the distance by the radius of thesphere (e.g. the Earth) in the same units as the distancemeasurement.
  • radians to distance: multiply the radian measure by the radiusof the sphere (e.g. the Earth) in the units system that you want toconvert the distance to.

The equatorial radius of the Earth is approximately 3,963.2miles or 6,378.1 kilometers.

The following query would return documents from the placescollection within the circle described by the center [ -74, 40.74 ]with a radius of 100 miles:

  1. db.places.find( { loc: { $geoWithin: { $centerSphere: [ [ -74, 40.74 ] ,
  2. 100 / 3963.2 ] } } } )

Note

If specifying latitude and longitude coordinates, list thelongitude first and then latitude:

  • Valid longitude values are between -180 and 180, bothinclusive.
  • Valid latitude values are between -90 and 90, bothinclusive.