【问题标题】:Apply $geoNear to find nearest latlong using aggregation in pymongo?应用 $geoNear 在 pymongo 中使用聚合查找最近的 latlong?
【发布时间】:2016-06-27 03:59:02
【问题描述】:

我的集合中的文档如下所示 -

{'_id' : 'Delhi1', 'loc' : [28.34242,77.656565] }
{'_id' : 'Delhi2', 'loc' : [27.34242,78.626523] }
{'_id' : 'Delhi3', 'loc' : [25.34242,77.612345] }
{'_id' : 'Delhi4', 'loc' : [28.34242,77.676565] }

我想使用 pymongo 应用聚合,以根据输入 latlong 找出相关文档。我已经在“loc”上创建了索引。这是我到目前为止所做的 -

pipeline = [{'$geoNear':{'near': [27.8787, 78.2342],
                     'distanceField': "distance",
                     'maxDistance' : 2000 }}]
db['mycollection'].aggregate(pipeline)

但这对我不起作用?如何正确使用它?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    您似乎有一些格式错误:1) 集合和运算符都不需要圆括号或方括号,2) 逻辑运算符是小写的。

    db.mycollection.aggregate([
        {
            $geoNear: {
                near: { coordinates: [ 27.8787 , 78.2342 ] },
                distanceField: "distance",
                maxDistance: 2000,
                spherical: true
            }
        }
    ])
    

    【讨论】:

    • 不,在pymongo中,我们需要将集合名称和运算符名称包裹在括号内,2 - 在python中逻辑运算符是Propercase
    • 最值得注意的是near: { coordinates: [ 27.8787 , 78.2342 ] } 是无效的。 "near" 选项“直接”采用坐标数组或 GeoJSON 对象 { "type": "Point", "coordinates": [ 27.8787 , 78.2342 ] }。 @userxxx 回答了自己的问题,添加了 "spherical": True,在 Python 中,“布尔值”的正确形式是 TrueFalse。阅读问题时注意标签(不要忘记在问题标题和正文中都使用了 pymongo)。 Python 与 JSON 和 JavaScript 有“相似”的语法,但有区别。
    【解决方案2】:

    实际上,我在集合中创建了 '2dsphere' 索引,并且要将 geoNear 与 2dsphere 一起使用,我们需要在管道中指定,spherical = True

    pipeline = [{'$geoNear':{'near': [27.8787, 78.2342],
                     'distanceField': "distance",
                     'maxDistance' : 2000,
                     'spherical' : True }}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2013-04-29
      相关资源
      最近更新 更多