Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a geospatial query in Mongo?

In the docs, it says that by default, Mongo treats it as lat/long:

By default, the index assumes you are indexing latitude/longitude and is thus configured for a [-180..180] value range.

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

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

I ensure my index:

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

Now, how do I execute the following in Mongo?

  • Give me all documents that are within 5 miles of a certain lat/long
  • Give me all documents within 400 meters of a certain lat/long
like image 909
TIMEX Avatar asked Dec 31 '10 07:12

TIMEX


1 Answers

Use $near in conjuction with $maxDistance:

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

The unit of $maxDistance is the same as the loc field, i.e. degrees. A degree is approximately 69 miles or 111 km at the equator, if I remember correctly (but it is less at other latitudes, the exact distance is hard to calculate).

To get more information about the returned locations, you can use the geoNear command, which will tell you the distance of all returned collections, among other things. 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).

like image 94
Theo Avatar answered Nov 07 '22 01:11

Theo