Mongodb Query for finding distance between latitude and longitude points

geocodinggeolocationmongodbmongodb-querymongoose

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.

Best Answer

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.

Related Topic