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:

 "address": "some_address",
    "city": "some_city",
    "coordinates": [
      32.214048,
      -84.361727
    ]

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
    {
        "address": "some_address",
        "city": "some_city",
        "coordinates": [
          -84.361727,
          32.214048
        ]
    }
  1. Once you have your data properly set, you must create a 2dsphere index in order to work with geoNear.
    db.collection.createIndex({coordinates: "2dsphere"})
  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]
    db.collection.find({ 
        coordinates: { 
            $nearSphere: { 
                $geometry: { 
                    type: "Point", 
                    coordinates: [ -84.361727 , 32.214048 ] 
                }, 
                $maxDistance: 100 
            } 
        } 
    }) 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement