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?
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?
Share Improve this question edited Nov 1, 2021 at 14:55 Etienne Martin 11.6k3 gold badges39 silver badges49 bronze badges asked Jun 30, 2016 at 1:03 ClipClip 3,0789 gold badges43 silver badges78 bronze badges1 Answer
Reset to default 11There are three main things you must do.
- 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
]
}
- Once you have your data properly set, you must create a 2dsphere index in order to work with geoNear.
db.collection.createIndex({coordinates: "2dsphere"})
- 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
}
}
})