我读了这些文档,不太清楚两者之间有什么区别。
我所发现的唯一不同之处是,在nearSphere中,它明确指出,Mongo使用球面几何来计算$nearSphere的距离。但是使用$near也可以实现这一点,不是吗?
发布于 2017-05-05 05:03:35
关键字是sphere,用于区分$near和$nearSphere。
如你所知,$nearSphere是用球面几何来计算距离的。这与地球问题( 地图投影,失真度)有关。其中MongoDB 2d指数是基于笛卡尔的,MongoDB 2 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 ] });这两个操作符的手册指定我们可以使用:
索引:2 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"}
]请参阅上述示例的要点: JS测试脚本。这是使用MongoDB v3.4.4进行测试的。
也见地理空间索引和查询。
https://stackoverflow.com/questions/38287374
复制相似问题