如何在PyMongo中使用$ geoNear和aggregate

时间:2017-06-16 07:39:24

标签: python mongodb pymongo

想象一下,你有一个具有以下结构的集合:

{
    "_id": ObjectId("543f1ec50204444c53ba39a0"), 
    "request_ip": "61.111.36.11", 
    "owner": ObjectId("543f227c0204444c53ba4b28"),
    "loc": [-116.199, 43.6186]
}

其中loc包含分别由其纬度和经度定义的地理点的位置。

嗯,您需要的是根据您的位置和另一个给定点之间的距离来查找集合中的文档。

在这种情况下,使用aggregate ()函数:

cercanos = collection.aggregate(
[{ 
    "$geoNear": {
        "near": [ 52.15077 , 9.95112 ],
        "distanceField": "dist", 
        "spherical": True,
        "limit":2
    }
}])

当您按照MongoDB文档(https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear)时,一切似乎都是有序的,但是当您运行多个错误时会出现:

  Traceback (most recent call last):
  File "E:\Documents\EclipseProjects\Bonus8\src\pru.py", line 154, in <module>
    "spherical": True,
  File "D:\Python\lib\site-packages\pymongo\collection.py", line 1870, in aggregate
    collation=collation)
  File "D:\Python\lib\site-packages\pymongo\collection.py", line 232, in _command
    collation=collation)
  File "D:\Python\lib\site-packages\pymongo\pool.py", line 419, in command
    collation=collation)
  File "D:\Python\lib\site-packages\pymongo\network.py", line 116, in command
    parse_write_concern_error=parse_write_concern_error)
  File "D:\Python\lib\site-packages\pymongo\helpers.py", line 210, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: geoNear command failed: { ok: 0.0, errmsg: "no geo indices for geoNear" }

1 个答案:

答案 0 :(得分:0)

会发生什么:

问题是MongoDB参考手册提供的用法示例特定于控制台中的独占执行(mongo shell)。这会导致在 PyMongo 环境中进行重大更改,例如必须引用变量。

可能的解决方案:

创建地理空间索引:

from pymongo import GEO2D
collection.create_index([("loc", GEO2D)])

这指定了一个二维地理空间索引,并解决了以前发生的错误。

<强>输出:

{
    "_id": ObjectId("543f1ec50204444c53ba39a0"), 
    "request_ip": "61.111.36.11", 
    "owner": ObjectId("543f227c0204444c53ba4b28"),
    "loc": [-116.199, 43.6186]
    "dist": 2.18848713
}