Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

Query for Locations within a Circle on a Sphere

On this page

  • About this Task
  • Before You Begin
  • Procedure
  • Learn More

You can query for location data within a circle on the surface of a sphere. Use these queries to return data within a spherical cap.

To query for location data within a circle on a sphere, use $geoWithin with the $centerSphere operator. In the $centerSphere operator, specify the coordinates and radius of the circle to query within:

db.<collection>.find( {
<location field> : {
$geoWithin : {
$centerSphere: [
[ <longitude>, <latitude> ],
<radius>
]
}
}
} )
  • When you specify longitude and latitude coordinates, list the longitude first, and then latitude.

    • Valid longitude values are between -180 and 180, both inclusive.

    • Valid latitude values are between -90 and 90, both inclusive.

  • In the $centerSphere operator, specify the circle's radius in radians. To convert other units to and from radians, see Convert Distance to Radians for Spherical Operators.

    • This example calculates distance in kilometers. To convert kilometers to radians, divide the kilometer value by 6378.1.

  • $geoWithin does not require a geospatial index. However, a geospatial index improves query performance. Only the 2dsphere geospatial index supports $geoWithin. For more information see Create a 2dsphere Index.

Create a places collection that contains these documents:

db.places.insertMany( [
{
loc: { type: "Point", coordinates: [ -73.97, 40.77 ] },
name: "Central Park",
category : "Park"
},
{
loc: { type: "Point", coordinates: [ -73.88, 40.78 ] },
name: "La Guardia Airport",
category: "Airport"
},
{
loc: { type: "Point", coordinates: [ -1.83, 51.18 ] },
name: "Stonehenge",
category : "Monument"
}
] )

To query the collection, use $geoWithin with the $centerSphere operator:

db.places.find( {
loc: {
$geoWithin: {
$centerSphere: [
[ -1.76, 51.16 ],
10 / 6378.1
]
}
}
} )

The query returns documents where the loc field is within a 10 kilometer radius of a point at longitude -1.76, latitude 51.16.

Output:

[
{
_id: ObjectId("63fd205e4a08b5e248c03e32"),
loc: { type: 'Point', coordinates: [ -1.83, 51.18 ] },
name: 'Stonehenge',
category: 'Monument'
}
]
← Query for Locations that Intersect a GeoJSON Object