I'm trying to query MongoDB geo
using $maxDistance
. But its not working in both PyMongo
and AsyncMongo
AsyncMongo
self.application.asyncdb.places.find({"loc":{"$near":[longitude, latitude], "$maxDistance":1000}}, limit=20, callback=self.showNearByPlaces)
PyMongo
placeColl = self.application.db.places
cursorObj = placeColl.find({"loc": {"$near":(longitude, latitude)},"$maxDistance":1000})
Here's an example using PyMongo 2.6.3 and MongoDB 2.4.8:
>>> from pymongo import MongoClient
>>> from bson import SON
>>> c = MongoClient()
>>> collection = c.db.collection
>>> collection.drop()
>>> collection.create_index([('loc', '2d')])
u'loc_2d'
>>> collection.insert({'loc': [1, 1]})
ObjectId('52d19a5eca1ce961b94f23f4')
>>> collection.insert({'loc': [3, 3]})
ObjectId('52d19a69ca1ce961b94f23f5')
>>> list(collection.find({'loc': SON([('$near', [0, 0]), ('$maxDistance', 2)])}))
[{u'loc': [1, 1], u'_id': ObjectId('52d19a5eca1ce961b94f23f4')}]
You can see that the point within 2 units of [0, 0] is included in the results, and the farther point is excluded.
Unlike most MongoDB queries, $near
queries require the keys to be in a particular order. $near
must come before $maxDistance
, not after. Since regular Python dicts don't preserve the order of the keys, I used a bson.SON
, which is installed as part of the PyMongo package. SON
is like a dictionary but preserves order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.