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

21

我看了文档,不太清楚这两者之间的区别。

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


1
我有完全相同的疑问。你找到了什么吗? - Gp2mv3
1个回答

26

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

如您所知,$nearSphere的计算距离使用球面几何。这与地球的地图投影畸变)有关。在MongoDB 2d索引中使用的是笛卡尔坐标系,而在MongoDB 2dsphere索引中则使用大圆

够理论了,让我们举些例子。假设我们有两个文档如下:

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索引用于被定义为传统坐标对的位置数据

索引: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"}
]

查看上述示例的 JavaScript 测试脚本,请参阅gist: JS test script。此示例使用的是 MongoDB v3.4.4 进行测试。

还请参阅地理空间索引和查询


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接