mongodb - 在 Mongo 中,$near 和 $nearSphere 有什么区别?

标签 mongodb

我阅读了文档,并不太清楚两者之间的区别。

我发现的唯一区别是,在 nearSphere 中,它明确表示 Mongo 使用球面几何计算 $nearSphere 的距离。但这也可以使用 $near 来实现,不是吗?

最佳答案

关键字是sphere来区分$near$nearSphere .

如您所知,$nearSphere 被声明为使用球面几何计算距离。这与地球有关map projection (distortion)。在哪里 MongoDB 2d indexes基于 CartesianMongoDB 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

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"}
]

gist: JS test script上面的例子。这是使用 MongoDB v3.4.4 测试的。

另见 Geospatial Indexes and Queries .

关于mongodb - 在 Mongo 中,$near 和 $nearSphere 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287374/

相关文章:

mongodb - 如何在 2.6 中向 Mongo 添加管理员用户?

mongodb - 多更新在 MongoDB 中不起作用

javascript - Mongoose 难以理解如何正确使用 promises/async await

mongodb - 获取字符串日期之间的数据 MongoDB

javascript - 嵌套 promise Node js

Node.js 将自定义对象序列化/反序列化到 mongodb

c# - 使用 Mongo C# 2.0 驱动程序替换嵌入式文档

mongodb:如何备份mongodb

java - 使用 java 将超过 16mb 的文档插入 Mongo db 3.0

ruby-on-rails - 使用长度标准查询 MongoDB