我阅读了文档,并不太清楚两者之间的区别。
我发现的唯一区别是,在 nearSphere 中,它明确表示 Mongo 使用球面几何计算 $nearSphere 的距离。但这也可以使用 $near 来实现,不是吗?
最佳答案
关键字是sphere
来区分$near和 $nearSphere .
如您所知,$nearSphere
被声明为使用球面几何计算距离。这与地球有关map projection (distortion)。在哪里 MongoDB 2d indexes基于 Cartesian和 MongoDB 2dsphere indexes基于 Geodesic .
足够的理论,让我们举一些例子。假设我们有两个文件如下:
db.map.insert({ "_id": "Westfield London", "location": [ -0.22157, 51.507176 ] });
db.map.insert({ "_id": "Green Lanes Shopping Centre", "location": [ -0.098092, 51.576198 ] });
两个运算符的手册都指定我们可以使用:
2dsphere
位置数据索引,定义为 GeoJSON积分2d
位置数据的索引,定义为 legacy coordinate pairs
索引:2dsphere,查询: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 ]}}}});
在这种情况下,两个查询将返回相同的结果,因为索引存储在 2dsphere
中。
结果:
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
索引:2d,查询:旧坐标
db.map.createIndex({"location": "2d"});
db.map.find({"location":{"$nearSphere":[ -0.127748, 51.507333 ]}});
db.map.find({"location":{"$near":[ -0.127748, 51.507333 ]}});
这就是区别发生的地方,尽管有索引,$nearSphere
的结果是球形计算的,而 $near
是在平面投影中计算的。
结果:
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Green Lanes Shopping Centre"},
{"_id" : "Westfield London"}
]
见 gist: JS test script上面的例子。这是使用 MongoDB v3.4.4 测试的。
关于mongodb - 在 Mongo 中,$near 和 $nearSphere 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287374/