I need to use an aggregate query to determine the distance between two places. Given that the $geoNear query was already used at the beginning of the query and that the distance needed to be calculated again for filterdown, we inserted the Haversine formula, however, the outcome is incorrect. any suggestions for how to fix this? The query samples are given below.
{
$addFields: {
lat1Radians: { $multiply: [36.7589882, Math.PI / 180] }, // Convert latitude1 to radians
lon1Radians: { $multiply: [-119.4249381, Math.PI / 180] }, // Convert longitude1 to radians
lat2Radians: { $multiply: [36.7151076, Math.PI / 180] }, // Convert latitude2 to radians
lon2Radians: { $multiply: [-119.4159583, Math.PI / 180] }, // Convert longitude2 to radians
},
},
{
$addFields: {
dlat: { $subtract: ['$lat2Radians', '$lat1Radians'] },
dlon: { $subtract: ['$lon2Radians', '$lon1Radians'] },
},
},
{
$addFields: {
a: {
$add: [
{ $sin: { $divide: ['$dlat', 2] } },
{
$multiply: [
{ $cos: '$lat1Radians' },
{ $cos: '$lat2Radians' },
{ $sin: { $divide: ['$dlon', 2] } },
],
},
],
},
},
},
{
$addFields: {
c: {
$atan2: [
{ $sqrt: { $max: ['$a', 0] } },
{ $sqrt: { $subtract: [1, '$a'] } },
],
},
},
},
{
$addFields: {
distanceH: { $multiply: [3959, '$c'] },
},
},
);