Skip to content

Instantly share code, notes, and snippets.

@buddyeorl
Created October 8, 2020 19:39
Show Gist options
  • Save buddyeorl/622bf4a3131db48354e203f0df119250 to your computer and use it in GitHub Desktop.
Save buddyeorl/622bf4a3131db48354e203f0df119250 to your computer and use it in GitHub Desktop.
Create a field in the result object"distance"
const getDistance=({lat, lon, query,sortOptions={distance:-1} })=>{
// implementation of the distance calculation using mongodb aggregate pipeline
//assuming there's a field called businessInfo and it's an object like {location:{lon:value, lat:value}}
let radlat1 = { $divide: [{ $multiply: [3.141592653589793238, lat] }, 180] };
let radlat2 = { $divide: [{ $multiply: [3.141592653589793238, "$businessInfo.location.lat"] }, 180] };
let theta = { $subtract: [lon, "$businessInfo.location.lon"] };
let radtheta = { $divide: [{ $multiply: [3.141592653589793238, theta] }, 180] };
let dist = { $sum: [{ $multiply: [{ $sin: radlat1 }, { $sin: radlat2 }] }, { $multiply: [{ $cos: radlat1 }, { $cos: radlat2 }, { $cos: radtheta }] }] };
dist = { $acos: dist };
dist = { $divide: [{ $multiply: [dist, 180] }, 3.141592653589793238] };
dist = { $multiply: [dist, 60, 1.1515] };
//if no sortOptions is received, the default value is sort by calculated distance, closest first
let sort = [
{ $sort: sortOptions },
{
$addFields: {
distance: dist
}
}
]
await collection.aggregate([
{ $match: query },
...sort
]).toArray((err, res)=>{
// process the result
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment