My company (Videntity) has been providing support to the Earth Institute (Columbia University). One of the tasks is to build a geospatial web service for tracking health facilities in the developing world. Its called You can think of it like a back-end database for displaying information in GoogleMaps and other mapping software. You can say things like, “Show me all the religious primary schools in Miga (Nigeria)” or “Show me all the water points in Ghana”. It returns data in GeoJSON format which is easy for many different Geographic Information Systems (GIS) to use as input.

Its a bit like, but its completely open source. is still a work in progress but coming together nicely. You can download the source code here.  Anyhow, I needed to support a geospatial search query with a maximum distance parameter.  After hours of trial and error and a few Internet hints here and there, I finally got it working.  Apparently, the trick is you need an ordered dictionary. This fact is not (as of this writing) in the MongoDB or pymongo documentation. This may seem simple enough but, alas you cannot order a dictionary (in Python) because a Python dictionary is just a mapping!  So we need to use the pymongo.son.SON package.  SON is a subclass of dict and preserves ordering. You can pass a SON object into pymongo’s find() method just like you would a standard Python dictionary.   Anyhow, here is a little example. I hope this helps someone else who stumbles on this problem. I was pulling my hair out for a few hours.

from pymongo import Connection
from pymongo.son import SON

def near_geoquery_with_max_distance(lat, lon, max_distance):
   """ Build the $near dict with your lat/lon values """
   near_dict = {'$near':[float(lat), float( lon)]}

   """ build the maxdistance dict with your max distance value """
   max_dist_dict={'$maxDistance': int(max_distance)}

   """ Create a SON object from our near_dict.

   """ Now add the 2nd item (max_dist_dict) to the ordered SON dict """

   """ Now put all of the above into a dict with using the key for your
       geospatial data
   gq={'location': q}

   """ Connect to the DB, use you local settings """
   mconnection =  Connection("MONGO_HOST", "MONGO_PORT")
   db =        mconnection["MONGO_DB_NAME"]
   transactions = db["COLLECTION_NAME"]
   """perform the search.  all should work now."""

Good Luck!