Mongodb 在Mongo中,$near和$nearSphere之间有什么区别?
我看了这些文件,不太清楚两者之间的区别Mongodb 在Mongo中,$near和$nearSphere之间有什么区别?,mongodb,Mongodb,我看了这些文件,不太清楚两者之间的区别 我发现的唯一区别是,在nearSphere中,它明确表示Mongo使用球形几何体计算$nearSphere的距离。但是使用$near也可以实现这一点,不是吗?关键字是sphere来区分和 如您所知,$nearSphere用于使用球形几何体计算距离。这与地球有关()。何处为基础,何处为基础 足够的理论,让我们用一些例子。假设我们有两份文件,如下所示: db.map.insert({ "_id": "Westfield London", "location":
我发现的唯一区别是,在nearSphere中,它明确表示Mongo使用球形几何体计算$nearSphere的距离。但是使用$near也可以实现这一点,不是吗?关键字是
sphere
来区分和
如您所知,$nearSphere
用于使用球形几何体计算距离。这与地球有关()。何处为基础,何处为基础
足够的理论,让我们用一些例子。假设我们有两份文件,如下所示:
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
位置数据索引定义为2d
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"}
]
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Green Lanes Shopping Centre"},
{"_id" : "Westfield London"}
]
索引: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" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $nearSphere */
{"_id" : "Westfield London"},
{"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
{"_id" : "Green Lanes Shopping Centre"},
{"_id" : "Westfield London"}
]
请参见上面示例的一部分。这是使用MongoDB v3.4.4进行测试的
另见 我有完全相同的审问。你找到什么了吗?