How to run geospatial query in Mongo?

The docs say that by default Mongo treats it as lat / long:

By default, the index assumes that you are indexing latitude / longitude and thus the range of values ​​configured for [-180..180].

So let's say I have this in my document:

post['loc'] = [ -40.234, 56.222] db.mycollection.save(post) 

I guarantee my index:

 db.mycollection.ensureIndex({"loc":"2d"}) 

Now, how do I do the following in Mongo?

  • Give me all documents that are within 5 miles of a specific lat / long
  • Give me all documents within 400 meters of a specific lat / long
+6
database indexing mongodb
source share
1 answer

Use $near in combination with $maxDistance :

 db.mycollection.find({loc: {$near: [50, 50], $maxDistance: 5}}) 

The unit $maxDistance matches the loc field, that is, degrees. The degree is about 69 miles or 111 km at the equator, if I remember correctly (but at other latitudes less, the exact distance is difficult to calculate).

To get more information about returned locations, you can use the geoNear command, which, among other things, will tell you the distance of all returned collections. See http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geoNearCommand

I think you can also use $geoWithin to solve your problem:

 db.mycollection.find({loc: {$geoWithin: {$center: [[50, 50], 5/3959]}}}) 

This should find all locations within the circle centered at (50, 50) with a radius of 5/3959 degrees (i.e. 5 miles).

+6
source share

All Articles