Docs Menu
Docs Home
/ / /
PyMongo
/ /

Geospatial Indexes

On this page

  • Overview
  • Sample Data
  • Create a Geospatial Index

MongoDB supports queries of geospatial coordinate data using 2dsphere indexes. With a 2dsphere index, you can query the geospatial data for inclusion, intersection, and proximity. For more information about querying geospatial data, see Geospatial Queries.

To create a 2dsphere index, you must specify a field that contains only GeoJSON objects. For more details on this type, see the GeoJSON objects guide in the MongoDB Server manual.

The examples in this guide use the sample_mflix.theaters collection from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with PyMongo.

The location.geo field in the following sample document from the theaters collection in the sample_mflix database is a GeoJSON Point object that describes the coordinates of the theater:

{
"_id" : ObjectId("59a47286cfa9a3a73e51e75c"),
"theaterId" : 104,
"location" : {
"address" : {
"street1" : "5000 W 147th St",
"city" : "Hawthorne",
"state" : "CA",
"zipcode" : "90250"
},
"geo" : {
"type" : "Point",
"coordinates" : [
-118.36559,
33.897167
]
}
}
}

The following example creates a 2dsphere index on the location.geo field:

theaters.create_index(
[( "location.geo", "2dsphere" )]
)

MongoDB also supports 2d indexes for calculating distances on a Euclidean plane and for working with the "legacy coordinate pairs" syntax used in MongoDB 2.2 and earlier. For more information, see the Geospatial Queries guide in the MongoDB Server manual.

Back

Text Indexes