Skip to content
Advertisement

Find closest entries in MongoDB to coordinates

I am having a hard time finding items which are closest to a set of lat/lon.

My objects have their lat/lon stored as such:

JavaScript

This is the query I am currently using, when I use it I get no results back, not even an empty array.

collection.find({coordinates: {$near: [40.296898, -111.694647] }, $maxDistance:100})

How can I query my objects to find the closest ones?

Advertisement

Answer

There are three main things you must do.

  1. You must save your coordinates in in the [longitude, latitude] order. This is required by mongo as you can see in docs. So, your data must look like
JavaScript
  1. Once you have your data properly set, you must create a 2dsphere index in order to work with geoNear.
JavaScript
  1. Then you must fix your query. Here need to pass a $nearSphere with geometry properties, that is where you put your coordinates in the order we said before [longitude, latitude]
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement