Distance calculation in Mongo shell

221 views Asked by At

I have two collections with coordinates (lat, lon) in MongoDb. I need to calculate minimal distance in meters between them. How can i do it in shell (using RoboMongo)?

Here is city.col (~30000 cities):

{
"_id" : ObjectId("52fdea51085f2f7e1841608d"),
"id" : -510625,
"city" : "Краков",
"latitude" : 50.063,
"longitude" : 19.937,
"count_hotels" : 536,
"price_UAH" : 137,
"date_insert" : "[2014/01/09:01:08:04 PM]",
"country" : "Польша" }

And here is clients.col(~4 mln):

{
"_id" : ObjectId("52f9eab9d3000fc3e4ecea7d"),
"pid" : 301010781,
"aid" : -6,
"owner_id" : 119538923,
"src" : "http://cs314531.vk.me/v314531923/13e/oGT6wil16GU.jpg",
"src_big" : "http://cs314531.vk.me/v314531923/13f/ymqm17vTgUU.jpg",
"src_small" : "http://cs314531.vk.me/v314531923/13d/QtqDlwYUGYk.jpg",
"src_xbig" : "http://cs314531.vk.me/v314531923/140/1gjQA-lR4Jg.jpg",
"src_xxbig" : "http://cs314531.vk.me/v314531923/141/Eqq7ZCEAzoI.jpg",
"width" : 1280,
"height" : 960,
"text" : "",
"created" : 1366279396,
"lat" : 49.553523,
"long" : 25.594753,
"post_id" : 1024,
"likes" : {
    "user_likes" : 0,
    "count" : 58
}}

And this is what i/m trying to do:

var d = Math.sqrt( Math.pow((db.city.longitude-db.new_coord.long),2) +Math.pow((db.city.latitude-db.new_coord.lat),2) )
1

There are 1 answers

1
gtsouk On

Once you fetch the 2 documents you can calculate the Eucleadean distance

d = Math.sqrt( Math.pow(o1.lon-o2.lon,2) + Math.pow(o1.lat-o2.lat,2) );

And then convert it to meters:

d2 = (d / 111.12) * 1000;