Docs Menu
Docs Home
/
MongoDB Manual
/ / / /

Create a 2dsphere Index

On this page

  • Before You Begin
  • Procedure
  • Next Steps
  • Learn More

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:

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.

The following operation creates a 2dsphere index on the location field loc:

db.places.createIndex( { loc : "2dsphere" } )

After you create a 2dsphere index, you can use the index for geospatial queries. To learn more, see Query a 2dsphere Index.

Back

2dsphere Indexes

Next

Query a 2dsphere Index