Geospatial Indexing Example
See also
The MongoDB documentation on
Creating a geospatial index in pymongo is easy:
- >>> result = db.places.insert_many([{"loc": [2, 5]},
- ... {"loc": [30, 5]},
- ... {"loc": [1, 2]},
- ... {"loc": [4, 4]}])
- >>> result.inserted_ids
Note
If specifying latitude and longitude coordinates in , list the longitude first and then latitude.
Using the geospatial index we can find documents near another point:
Note
The $maxDistance operator requires the use of :
- >>> from bson.son import SON
- >>> query = {"loc": SON([("$near", [3, 6]), ("$maxDistance", 100)])}
- >>> for doc in db.places.find(query).limit(3):
- ... pprint.pprint(doc)
- ...
- {u'_id': ObjectId('...'), u'loc': [2, 5]}
- {u'_id': ObjectId('...'), u'loc': [4, 4]}
- {u'_id': ObjectId('...'), u'loc': [1, 2]}
It’s also possible to query for all items within a given rectangle(specified by lower-left and upper-right coordinates):
Or circle (specified by center point and radius):
- >>> for doc in db.places.find(query).sort('_id'):
- ... pprint.pprint(doc)
- ...
- {u'_id': ObjectId('...'), u'loc': [2, 5]}
- {u'_id': ObjectId('...'), u'loc': [1, 2]}
- {u'_id': ObjectId('...'), u'loc': [4, 4]}
geoNear queries are also supported using :
Starting in MongoDB version 4.0, MongoDB deprecates the geoNear command. Use one of the following operations instead.
- $geoNear - aggregation stage.
- $near - query operator.