我一直在考虑使用MongoDB而不是自定义地理空间数据库,但是我很难理解pymongo如何使用球坐标。 具体地说,我不确定$maxDistance(以及类似的设置是否有任何效果)。 例如,如果我执行此代码:
db = pymongo.MongoClient().geo_example
db.places.create_index([("location", pymongo.GEOSPHERE)])
cities = [{"location": {'type': 'Point', 'coordinates': [57, 2]}, "name": "Aberdeen"},
{"location": {'type': 'Point', 'coordinates': [52, 13]}, "name": "Berlin"},
{"location": {'type': 'Point', 'coordinates': [44, 26]}, "name": "Bucharest"},
{"location": {'type': 'Point', 'coordinates': [40, 14]}, "name": "Napoli"},
{"location": {'type': 'Point', 'coordinates': [48, 2]}, "name": "Paris"},
{"location": {'type': 'Point', 'coordinates': [35, -70]}, "name": "Tokyo"},
{"location": {'type': 'Point', 'coordinates': [47, 8]}, "name": "Zurich"}]
try:
result = db.places.insert_many(cities)
for doc in db.places.find( {"location":{'$nearSphere': [57, 2], "$maxDistance": 1}}).limit(3):
pprint.pprint(doc)
except BulkWriteError as bwe:
print(bwe.details)
我希望答案只是阿伯丁,相反,即使最大距离大于1米,我仍然能得到最近的3个。我想我做错了什么。 任何关于pymongo使用的帮助以及更好的示例(比文档中的更好)都会非常有用。 谢谢
您使用的是较旧的查询形式,其中以弧度指定距离。如果更改为new format,则
maxDistance
以米为单位指定此外,由于在时间迷雾中丢失的原因,地理空间数据按长/纬度顺序排序,因此所有坐标都需要反转。我已经修改了您的代码,使其使用正确的坐标方向,并使用新的查询格式。我还为集合输入了一个
drop
命令(这是示例代码)。这让我困惑,也可能让你困惑。多次运行 程序的所有部分将反复插入相同的点。毫不犹豫 每个查询将返回与您运行程序的次数相同的结果。最后,我添加了一个GEOSPHERE
索引,文档中说您需要这个索引,即使您的程序没有它也可以正常运行。我怀疑如果没有这一点,随着位置数量的增加,您将看到性能的几何下降相关问题 更多 >
编程相关推荐