gpt4 book ai didi

python + pymongo : how to insert a new field on an existing document in mongo from a for loop

转载 作者:IT老高 更新时间:2023-10-28 13:09:10 28 4
gpt4 key购买 nike

我在 python 中使用 for 循环来循环使用 pymongo 的查询结果。代码如下:

from pymongo import MongoClient
connection = MongoClient()
db = connection.Test

myDocs = db.Docs.find( { "geolocCountry" : { "$exists" : False } } )

for b in myDrives:
my_lat = b['TheGpsLog'][0]['latitude']
my_long = b['TheGpsLog'][0]['longitude']

myGeolocCountry = DoReverseGeocode(lat_start,long_start)
# Here I perform a reverse geocoding, it does not matter for this example.
# The important thing is: it returns a string, like 'US', 'UK', etc...

我的问题是,如何将变量 myGeolocCountry 插入到现有文档(b)上不存在的字段 geolocCountry ?

我试过了

b['geolocCountry'] = myGeolocCountry

但它根本不起作用,它甚至不会产生错误。

谢谢

最佳答案

您应该像这样执行更新查询:

db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})

关于python + pymongo : how to insert a new field on an existing document in mongo from a for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666169/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com