from pymongo import Connection, GEO2D
db = Connection().monspatial
# création de l'index spatial
db.montest.create_index([("loc", GEO2D)])
# insertion des points (simple)
db.montest.insert({"loc": [50.52, 4.42]})
db.montest.insert({"loc": [50.52, 5.42]})
db.montest.insert({"loc": [51.52, 3.42]})
# recherche find near, limitée
for doc in db.montest.find({"loc": {"$near": [50.00, 5.00]}}).limit(3):
repr(doc)
"{u'loc': [50.520000000000003, 5.4199999999999999], u'_id': ObjectId('4e5bc3c5c32e370848000001')}"
"{u'loc': [50.520000000000003, 4.4199999999999999], u'_id': ObjectId('4e5bc361c32e370848000000')}"
"{u'loc': [51.520000000000003, 3.4199999999999999], u'_id': ObjectId('4e5bc3d2c32e370848000002')}"
# recherche find within box
for doc in db.montest.find({"loc": {"$within": {"$box": [[50, 4.5], [51, 6.0]]}}}):
repr(doc)
"{u'loc': [50.520000000000003, 5.4199999999999999], u'_id': ObjectId('4e5bc3c5c32e370848000001')}"
# recherche geoNear
from bson.son import SON
>>> db.command(SON([('geoNear', 'montest'), ('near', [50.52, 4.42])]))
{u'ok': 1.0, u'near': u'1100100000001111101011001011000011101100000011001101', u'ns': u'monspatial.montest', u'stats': {u'btreelocs': 2, u'avgDistance': 0.80473870022961835, u'objectsLoaded': 3, u'time': 38, u'maxDistance': 1.4142134780844851, u'nscanned': 3}, u'results': [{u'obj': {u'loc': [50.520000000000003, 4.4199999999999999], u'_id': ObjectId('4e5bc361c32e370848000000')}, u'dis': 0.0}, {u'obj': {u'loc': [50.520000000000003, 5.4199999999999999], u'_id': ObjectId('4e5bc3c5c32e370848000001')}, u'dis': 1.0000026226043701}, {u'obj': {u'loc': [51.520000000000003, 3.4199999999999999], u'_id': ObjectId('4e5bc3d2c32e370848000002')}, u'dis': 1.4142134780844851}]}