我读了这些文件,不太清楚两者之间的区别.
我发现的唯一区别是,在nearSphere中,它明确表示Mongo使用球面几何计算$nearSphere的距离.但使用$near也是可以实现的,不是吗?
我读了这些文件,不太清楚两者之间的区别.
我发现的唯一区别是,在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 pairsIndex: 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 ]}}}});
在这种情况下,两个查询将返回相同的结果,因为索引存储在2dsphere
中.
结果:
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
Index: 2d , Query: Legacy Coordinates
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.