How to get or find closest entries in MongoDB

Published on Author Code Father

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 ] }

  2. Once you have your data properly set, you must create a 2dsphere index in order to work with geoNear.

    db.collection.createIndex({coordinates: “2dsphere”})

  3. 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 } } })