La parola chiave è sphere
per distinguere tra $near e $nearSphere.
Come sapete, $nearSphere
viene indicato per calcolare la distanza utilizzando la geometria sferica. Questo è collegato alla Terra map projection (distortion). Dove MongoDB 2d indexes è basato su Cartesian e MongoDB 2dsphere indexes è basato su Geodesic.
Basta teoria, usiamo alcuni esempi. Diciamo che abbiamo due documenti come qui sotto:
db.map.insert({ "_id": "Westfield London", "location": [ -0.22157, 51.507176 ] });
db.map.insert({ "_id": "Green Lanes Shopping Centre", "location": [ -0.098092, 51.576198 ] });
Il manuale sia per gli operatori specificare che possiamo utilizzare:
2dsphere
indice per i dati relativi all'ubicazione definiti come GeoJSON punti
2d
indice per i dati di posizione definito come legacy coordinate pairs
Indice: 2dsphere, Query: GeoJSON
db.map.createIndex({"location": "2dsphere"});
db.map.find({"location":{"$nearSphere":{"$geometry":{"type":"Point", "coordinates":[ -0.127748, 51.507333 ] }}}});
db.map.find({"location":{"$near":{"$geometry":{"type":"Point", "coordinates":[ -0.127748, 51.507333 ]}}}});
In questo caso, entrambe le query restituirà lo stesso risultato, perché l'indice è memorizzato in 2dsphere
.
Risultato:
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
Index: 2d, Query: Legacy Coordinate
db.map.createIndex({"location": "2d"});
db.map.find({"location":{"$nearSphere":[ -0.127748, 51.507333 ]}});
db.map.find({"location":{"$near":[ -0.127748, 51.507333 ]}});
Questo è dove la distinzione avviene, il risultato per $nearSphere
viene calcolato sferica, nonostante l'indice, mentre $near
è calcolato in proiezione piatta.
Risultato:
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Green Lanes Shopping Centre"},
{"_id" : "Westfield London"}
]
Vedi gist: JS test script dell'esempio precedente. Questo è stato testato usando MongoDB v3.4.4.
Vedere anche Geospatial Indexes and Queries.
Ho esattamente lo stesso interrogatorio. Hai trovato qualcosa? – Gp2mv3