我看了文档,不太清楚这两者之间的区别。
唯一发现的区别是在nearSphere中明确说明Mongo使用球面几何计算$nearSphere的距离。但是,使用$near也可以实现这一点,不是吗?
我看了文档,不太清楚这两者之间的区别。
唯一发现的区别是在nearSphere中明确说明Mongo使用球面几何计算$nearSphere的距离。但是,使用$near也可以实现这一点,不是吗?
关键字是sphere
,用于区分$near和$nearSphere。
如您所知,$nearSphere
的计算距离使用球面几何。这与地球的地图投影(畸变)有关。在MongoDB 2d索引中使用的是笛卡尔坐标系,而在MongoDB 2dsphere索引中则使用大圆。
够理论了,让我们举些例子。假设我们有两个文档如下:
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
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"}
]
查看上述示例的 JavaScript 测试脚本,请参阅gist: JS test script。此示例使用的是 MongoDB v3.4.4 进行测试。
还请参阅地理空间索引和查询。