In my MongoDB database I have tons of location (coordinates can be duplicated) . I'm trying to get the first nearest location (longitude / latitude). Inside my model I have this :
var mySchema = new Schema({
loc:{
type : [Number],
index: '2d'
},
...
});
I see than MongoDB implement $near
method to calculate the nearest locations. Then I tried this
Model.find({loc: {$near:[1.4072964, 7.826107], $maxDistance: 1} }, function(err, result){
result.forEach(function(doc){
console.log(doc.loc)
})
});
The problem is that it will returns all locations nearest to this point around 1 meter. But I don't need max distance I just want the first nearest location found.
I can't use findOne
for this because I need to get all duplicated data for this first location.
Eg If the first coordinate found is -5.95001220703125, 51.5499954223633
and I have this location 10 times, I need to get all documents with this locations.
So it's possible to do this with just once Mongoose Query ? Or I shouldn't use the MongoDB Geospatial Indexing and calculate the nearest distance myself in my application ?
I suggest divide your query in two parts:
To find the closest document you can use the $nearsphere
operator.
// you can use callbacks if you want
let closestQuery =
Person
.find({
loc: {
$nearsphere: coords
}
})
.limit(1)
.exec();
closestQuery.then(doc => ...);
Then you just need to find by the same location in order to fetch duplicates.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.