Geospatial Indexing Example

    See also

    The MongoDB documentation on

    geo

    Creating a geospatial index in pymongo is easy:

    1. ... {"loc": [30, 5]},
    2. ... {"loc": [1, 2]},
    3. ... {"loc": [4, 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 SON:

    1. >>> from bson.son import SON
    2. >>> for doc in db.places.find(query).limit(3):
    3. ... pprint.pprint(doc)
    4. ...
    5. {u'_id': ObjectId('...'), u'loc': [2, 5]}
    6. {u'_id': ObjectId('...'), u'loc': [4, 4]}
    7. {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):

    1. >>> for doc in db.places.find(query).sort('_id'):
    2. ... pprint.pprint(doc)
    3. ...
    4. {u'_id': ObjectId('...'), u'loc': [2, 5]}
    5. {u'_id': ObjectId('...'), u'loc': [1, 2]}
    6. {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.