我读了这些文件,不太清楚两者之间的区别.

我发现的唯一区别是,在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 ] });

两位操作员的手册都规定我们可以使用:

Index: 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.

另见Geospatial Indexes and Queries.

Mongodb相关问答推荐

无法配置数据源:未指定url属性,无法为 MongoDb 配置嵌入数据源

MongoDB:检测所有重叠事件(开始/结束日期)?

如何判断 mongodb 聚合,该文档具有键,该键是一个数组,其第二个元素是否存在?

通过 docker 运行的 MongoDB 服务器无法互相看到(名称解析中的临时故障)

根据聚合管道MongoDB Atlas触发器中的条件更新多个字段

在golang中的mongodb中的集合列表中打印集合

如何在 MongoDB 中存储时间?作为字符串?给出任意年/月/日?

为什么 MongoDB 配置服务器必须只有一个或三个?

MongoDB 使用自定义表达式或函数进行排序

Node.js 和 MongoDB,重用 DB 对象

什么是 mongodb 中的admin数据库?

如何使用 java 驱动程序更新 mongo db 中的文档字段?

mongodb-nodejs-driver,DeprecationWarning:collection.count 已弃用

如何使用 c# 2.0 驱动程序将数据插入到 mongodb 集合中?

MongoDB 3 Java判断集合是否存在

有没有办法为 mongoose.js 聚合提供 allowDiskUse 选项?

如何在mongodb中删除数组的第n个元素

Ruby 按键值分组哈希

brew install mongodb 错误:Cowardly refusing to `sudo brew install' Mac OSX Lion

查找聚合性能差