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
x
7
1
"address": "some_address",
2
"city": "some_city",
3
"coordinates": [
4
32.214048,
5
-84.361727
6
]
7
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.
- 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
9
1
{
2
"address": "some_address",
3
"city": "some_city",
4
"coordinates": [
5
-84.361727,
6
32.214048
7
]
8
}
9
- Once you have your data properly set, you must create a 2dsphere index in order to work with geoNear.
JavaScript
1
2
1
db.collection.createIndex({coordinates: "2dsphere"})
2
- 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
1
12
12
1
db.collection.find({
2
coordinates: {
3
$nearSphere: {
4
$geometry: {
5
type: "Point",
6
coordinates: [ -84.361727 , 32.214048 ]
7
},
8
$maxDistance: 100
9
}
10
}
11
})
12