You are viewing an offline version of MongoDB documentation. Some page features might be unavailable. To view the latest version of the page or use interactive features, visit the live page.
2dsphere indexes support geospatial queries on an earth-like sphere. For example, 2dsphere indexes can:
Determine points within a specified area.
Calculate proximity to a specified point.
Return exact matches on coordinate queries.
To create a 2dsphere index, use the
db.collection.createIndex() method and specify the string
"2dsphere" as the index type:
db.<collection>.createIndex( { <location field> : "2dsphere" } )
The values in the <location field> must be either:
Before You Begin
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" } ] )
The values in the loc field are GeoJSON points.
Procedure
The following operation creates a 2dsphere index on the location field
loc:
db.places.createIndex( { loc : "2dsphere" } )
Next Steps
After you create a 2dsphere index, you can use the index for geospatial queries. To learn more, see Query a 2dsphere Index.