1

I have a user's collection with Latitude and longitude points for each user.

I want to calculate distance between given Lat, long values and user's location.

In MYSQL there is a query for it

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

Is there any equivalent approach/ Query in mongodb? There are ways to accomplish this in Javascript but it would be better if coded in a Query.

Ramaraju.d
  • 1,301
  • 6
  • 26
  • 46

1 Answers1

2

Mongo does not provide you with easy field manipulations like you had in sql world. Some of the geospatial results give you back the distance as well, but for the task you want, I would rather do this calculation afterwards. There is a question on SO which targets you perfectly and among many answers I gave an optimized javascript solution.

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • Thanks for the links. The issue is i saved Long and lat values in two different fields. Later I realized and updated to [long,lat]. This worked and the JavaScript function is so simple and easy to understand. Thank you. – Ramaraju.d May 07 '15 at 09:04