Wednesday, November 6, 2013

Mongodb find locations within certain miles given a coordinate

Note: this has been tested with Mongodb 2.4

I recently got to work on a side project that needed to look for close by stores within 10 miles given a coordinate.

The stores collection already stored the latitude and longitude but they were not stored in the expected GeoJSON format, which is this:

{ "loc": [ -73.946922, 40.780182] }

or this is also acceptable

{ "loc" : [ "lng": -73.946922, "lat": 40.780182 ] }


Instead the collection I was working with had this:

{"lat" : 40.780182, "lng" : -73.946922 }

So first thing, I had to update the collection to add a new field, and set a new property called "loc" to store a coordinates array:

db.stores.find().forEach(function(doc){db.stores.update({_id: doc._id}, { $set: {loc: [doc.longitude, doc.latitude] }})});

Then build an index

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


Then, after that, say you want to find all stores that is within 5 miles of a given set of coordinate, in mongodb 2.4, all you have to do is issue this command:

db.stores.find( { loc: { $geoWithin: { $centerSphere: [ [ -122.0751549, 37.386812 ] , 5 / 3959 ] } } } );

Note: why divide by 3959? The radius of the Earth is approximately 3,959 miles.

No comments:

Post a Comment