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

1

7

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?

Ingathering answered 6/4, 2011 at 17:18 Comment(0)
I
10

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
Ingathering answered 6/4, 2011 at 17:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.