首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在蒙古族,$near和$nearSphere有什么区别?

在蒙古族,$near和$nearSphere有什么区别?
EN

Stack Overflow用户
提问于 2016-07-10 00:02:27
回答 1查看 5.8K关注 0票数 21

我读了这些文档,不太清楚两者之间有什么区别。

我所发现的唯一不同之处是,在nearSphere中,它明确指出,Mongo使用球面几何来计算$nearSphere的距离。但是使用$near也可以实现这一点,不是吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-05 05:03:35

关键字是sphere,用于区分$near$nearSphere

如你所知,$nearSphere是用球面几何来计算距离的。这与地球问题( 地图投影失真度)有关。其中MongoDB 2d指数是基于笛卡尔的,MongoDB 2 2dsphere索引是基于测地线的。

理论够多了,让我们举几个例子。假设我们有两份文件如下:

代码语言:javascript
复制
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

代码语言:javascript
复制
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中。

结果:

代码语言:javascript
复制
[ /* $nearSphere */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]

索引: 2d,查询:遗留坐标

代码语言:javascript
复制
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是用平面投影计算的。

结果:

代码语言:javascript
复制
[ /* $nearSphere */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
    {"_id" : "Green Lanes Shopping Centre"},
    {"_id" : "Westfield London"}
]

请参阅上述示例的要点: JS测试脚本。这是使用MongoDB v3.4.4进行测试的。

也见地理空间索引和查询

票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38287374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档