Geospatial Indexes
Overview
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.
Sample Data
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 ] } } }
Create a Geospatial Index
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.
Collation
When you create an index, you can specify a default collation for all operations you perform on fields that are included in the index.
A collation is a set of language-specific rules for string comparison, such as for letter case and accent marks.
To specify a collation, create an instance of the Collation
class or a Python dictionary.
For a list of options to pass to the Collation
constructor or include as keys in the
dictionary, see Collation in the MongoDB Server manual.
Tip
Import Collation
To create an instance of the Collation
class, you must import it from
pymongo.collation
.
To use an index with a specified collation, your operation must meet the following criteria:
The operation uses the same collation as the one specified in the index.
The operation is covered by the index that contains the collation.
The following example creates the same index as the previous example,
but with a default collation of fr_CA
:
from pymongo.collation import Collation theaters.create_index( [( "location.geo", "2dsphere" )], collation=Collation(locale='fr_CA'))