Ceci devrait convenir : un filtrage $geoWithin sur la boîte, puis un calcul de Haversine par rapport à votre point de référence :
db.collection.aggregate([
{ "$match": {
"location": {
"$geoWithin": {
"$box": [
[0.024719919885622943, 51.54643953472475],
[-0.1589577534542408, 51.47239969138267]
]
}
}
} },
{ $set: { lon: -0.0649729793707321 } },
{ $set: { lat: 51.50160291888072 } },
{ $set: { distance: { $let: {
vars: {
dlon: { $degreesToRadians: { $subtract: [
{ $arrayElemAt: ["$location.coordinates", 0] }, "$lon" ] } },
dlat: { $degreesToRadians: { $subtract: [
{ $arrayElemAt: ["$location.coordinates", 1] }, "$lat" ] } },
lat1: { $degreesToRadians: { $arrayElemAt: ["$location.coordinates", 1] } },
lat2: { $degreesToRadians: "$lat" }
},
in: {
// Haversine : sin²(dLat/2) + sin²(dLon/2) * cos(lat1) * cos(lat2)
$add: [
{ $pow: [{ $sin: { $divide: ["$$dlat", 2] } }, 2] },
{ $multiply: [
{ $pow: [{ $sin: { $divide: ["$$dlon", 2] } }, 2] },
{ $cos: "$$lat1" },
{ $cos: "$$lat2" }
] }
]
}
} } } },
{ $set: { distance: {
// mètres : 6372.8 * 1000
$multiply: [6372.8, 1000, 2, { $asin: { $sqrt: "$distance" } }]
} } }
])
Attention à l'index
$box ne s'applique qu'aux anciennes paires de coordonnées. Pour une requête moderne, indexée, utilisez $geometry avec un index 2dsphere :
db.collection.createIndex({ location: "2dsphere" })
db.collection.find({
"location": {
"$geoWithin": {
"$geometry": {
type: "Polygon",
coordinates: [[
[-0.1589577534542408, 51.47239969138267],
[-0.1589577534542408, 51.54643953472475],
[0.024719919885622943, 51.54643953472475],
[0.024719919885622943, 51.47239969138267],
[-0.1589577534542408, 51.47239969138267]
]]
}
}
}
}).explain().queryPlanner.winningPlan.inputStage.indexName
--> location_2dsphere (index utilisé)
db.collection.find({
"location": {
"$geoWithin": {
"$box": [
[0.024719919885622943, 51.54643953472475],
[-0.1589577534542408, 51.47239969138267]
]
}
}
}).explain().queryPlanner.winningPlan.stage
--> COLLSCAN (balayage complet)
Ou, si vous devez vraiment conserver les coordonnées historiques, indexez explicitement le sous-champ :
db.collection.createIndex({ "location.coordinates": "2d" })
db.collection.find({
"location.coordinates": {
// notez la différence
"$geoWithin": {
"$box": [
[0.024719919885622943, 51.54643953472475],
[-0.1589577534542408, 51.47239969138267]
]
}
}
}).explain().queryPlanner.winningPlan.inputStage.indexName
--> location.coordinates_2d
La sortie de .explain() est le vrai juge de paix : si vous voyez COLLSCAN, votre requête géométrique n'utilise pas l'index prévu.