Answer the question
In order to leave comments, you need to log in
Geo search in MongoDB?
I'm working on a search for location-based data in MongoDB. For example, there is a list of users and for each the coordinates are indicated in the form of longitude, latitude. It is necessary to sort users depending on the distance to a particular point [longitude, latitude] + display the distance.
I do everything using the built-in geosearch MongoDB + Mongoose like this:
User.aggregate([
{
$geoNear: {
near: [latitude, longitude],
distanceField: "distance",
distanceMultiplier: 1000*1000,
maxDistance: 1/111.12,
spherical:true
}
}
]);
Answer the question
In order to leave comments, you need to log in
var maxDistance = Number(query.distance);
var limit = Number(query.limit);
var page = Math.max(0, query.page);
var loc = [];
loc[0] = Number(query.lon);
loc[1] = Number(query.lat);
User.find({
loc: {
$near: loc,
$maxDistance: maxDistance
}
}).limit(limit).skip(limit * page).sort({username: 'asc'}).exec(function(err, locations) {
// ....
});
// User schema
/*
....
loc: {
type: [Number],
index: '2d'
}
....
*/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question