I had the need to store and query coordinates on a map for displaying them on Google Maps on a node.js application that I was working on. Using Mongo DB and the “mongodb” module, it was really a breeze.
The collection can store the coordinates using any key inside the document. The only condition is that the coordinates are represented by an array of size 2, in the order, [longitute. latitude]. A sample document would look like this.
{ "coords" : [ 80.1572101031494, 12.50809389399446 ], "name" : "Milcom", "_id" : ObjectId("53ae5876cad6c38f09089251") }
Once that is done, we need to ensure that an index is created for that property in our collection. For example, if the property name is coords, the following needs to be executed after initiating the connection.
db.collection('collection_name').ensureIndex({coords: "2d"}, function () {console.log("Index ensured.")}); //Can be executed any number of times.
The query needs to convert the radius, in kilometer, to the corresponding degree value. This is done as follows
db.collection("collection_name", function (err, collection) { //1/111.12 is the equivalent degree change for one km according to //stackoverflow.com/questions/7837731/units-to-use-for-maxdistance-and-mongodb/7841830#7841830 collection.find({coords: {$near: [longitude, latitude], $maxDistance: radius / 111.12}}).toArray(function (err, docs) { console.log(docs); //Insert logic here. }); });
It’s amazing how such wonderful techniques are available OOTB to us.