Reputation: 271584
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?
Upvotes: 6
Views: 2702
Reputation: 132862
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).
Upvotes: 6