Docs Menu

Docs HomeMongoDB Manual

# Query for Locations within a Circle on a Sphere.css-134mg1q{-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;padding:0 10px;visibility:hidden;}.css-6vrlzm{border-radius:0!important;display:initial!important;margin:initial!important;}.css-1l4s55v{margin-top:-175px;position:absolute;padding-bottom:2px;}

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.

`.leafygreen-ui-1xcl9uc{color:inherit;font-size:13px;font-family:'Source Code Pro',Menlo,monospace;line-height:24px;font-size:15px;}`.leafygreen-ui-1v41da1{border-spacing:0;width:100%;}.leafygreen-ui-7razhx{border-spacing:0;vertical-align:top;padding:0 16px;}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 Object2dsphere Index Versions →
Share Feedback