Search code examples
mongodbgeospatialdjango-nonrel

How to make a custom query using django-nonrel and mongodb


Is there a recommended way to make a custom query to mongodb using django nonrel?

I have an entire site set up and running well, now I am just adding in some geospatial indexing and queries, and wanted to know if for geospatial queries there is already support or if there is a best practice way to do it using a custom made query?


Solution

  • I found one answer to this question, let me now if there is a better one.

    As documented here assign your objects to the MongoDBManager - http://django-mongodb-engine.github.com/mongodb-engine/cool-stuff.html#included-mongodb-batteries

    from django_mongodb_engine.contrib import MongoDBManager
    
    class MyModel(models.Model):
        objects = MongoDBManager()
    

    Then you can do raw queries like this:

    MyModel.objects.raw_query({'loc' : {'$near' : [50,50]}})
    

    A different approach I guess would be to go directly to pymongo: http://api.mongodb.org/python/1.10%2B/examples/geo.html

    Finally I ended up with this query:

    nearest = MyModel.objects.raw_query(
        {'loc' : {
             '$within' :{ #within .05 degrees of lat/lon
                        '$center' : [{'long' : long,'lat' : lat}, .05]
                        }
          })[:10] #get up to 10 results