【问题标题】:pymongo update location datapymongo 更新位置数据
【发布时间】:2014-06-13 04:15:29
【问题描述】:

我想更新一个包含 lat,lng 值的数组。下面给出了我的来自 python 的更新查询。

client.mydb.mycoll.update({"_id":123},{'$push':{"loc":{"lng":77.77,"lat":12.12}}} )

集合已经在“loc”数组中有一些值,如下所示

{ "_id" : 123, "loc" : [    {   "lng" : 77.6104193,     "lat" : 12.9264116 } ], "name" : "myname" }

更新查询的问题在于它将新的“loc”元素存储为

{ "_id" : 123, "loc" : [ { "lng" : 77.6104193, "lat" : 12.9264116 },{"lat":12.12,"lng":77.77} ], "name" : "myname " }

我需要按“lng”拳头然后“lat”的顺序存储 loc 数据。这样以后,我可以使用 $near 运算符 ({loc:{$near:[77.77,12.12]}}) 进行查询。 python字典总是存储按key排序的键值对,我该怎么做呢?

【问题讨论】:

    标签: python mongodb dictionary geolocation


    【解决方案1】:

    我建议稍微改变结构以匹配 MongoDB manual:

    coordinates : [ <longitude> , <latitude> ]
    

    所以你最终会得到这样的结果:

    { "_id" : 123, "loc" : [ [77.6104193, 12.9264116], [77.77, 12.12] ], "name" : "myname" }
    

    MongoDB 保持数组的顺序,但不保证保持对象字段的顺序 (See this answer to a similar question)。

    【讨论】:

    • 我不能这样做,因为表中已经有使用php代码的数据。我正在从php转移到python
    【解决方案2】:

    经过一番研究,我在 python 文档中找到了OrderedDict

    from collections import OrderedDict
    
    client.mydb.mycoll.update({"_id":123},{'$push':{"loc":OrderedDict((("lng",77.77),("lat":12.12)))}} )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      相关资源
      最近更新 更多