3
votes

I've recently upgraded my MongoDB from version 2.2.1 to version 2.4.6, and pymongo to 2.6.2.

One of the reasons for the upgrade is the capability of the new version of MongoDB to calculate and return the distance of the documents (which include proper coordinates) from the center of a geospatial query as explained here.

So far I execute the following query:

db.collection.find({"loc": {"$within": {"$center": [[LON, LAT], RADIUS]}}})

where LON, LAT and Radius are proper numbers. I then programmatically calculate the distance from the center for each document returned.

Now I'm trying to have MongoDB to do the distance calculations on my behalf, because of higher efficiency compared to my code.

What I'm trying now is the following:

db.collection.find({"loc": {"$geoWithin": {"$centerSphere": [[LON, LAT], RADIUS]}}})

where RADIUS is now calculated properly (radius in km / 6371), but I get the same results as the older query.

How should I change the new query in order to get returned the extra field "dis" per every document returned?

The geospatial index is 2D, which should work according to docs, but I can change it to 2dsphere if necessary. Does anyone have a good suggestion?

1

1 Answers

3
votes

Try using the $geoNear command in the aggregation framework. The $geoNear documentation is here:

http://docs.mongodb.org/manual/reference/aggregation/geoNear/

Your query will end up looking like:

db.collection.aggregate([{$geoNear:{near:[LON,LAT],distanceField:"distance",maxDistance:RADIUS,spherical:true}}])

and the resulting documents will have a field named "distance" with the calculated value. Hope that helps.