[英]python + pymongo: how to insert a new field on an existing document in mongo from a for loop
我在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}})
您必須使用函數update()
才能更新集合中的記錄。
使用更新,您可以指定一個查詢(就像您在上面使用collection.find()
但也提供了第二個dict,它定義了如何更新查詢中找到的文檔。例如:
db.Docs.update({"geolocCountry":{"$exists":False}}, {"$set": "geolocCountry": myGeolocCountry})
查看其余參數的API。
對於pymongo> 3
db.Doc.update_one({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
如果有多個更新:
db.Doc.update_many({"geolocCountry": {"$exists": False}}, {"$set": {"geolocCountry": myGeolocCountry}})
對於pymongo <3
上面/先前的答案是正確的
db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
如果有多個更新:
db.Doc.update({"geolocCountry": {"$exists": False}}, {"$set": {"geolocCountry": myGeolocCountry}})
您需要在更新后保存集合。
for b in myDrives:
my_lat = b['TheGpsLog'][0]['latitude']
my_long = b['TheGpsLog'][0]['longitude']
myGeolocCountry = DoReverseGeocode(lat_start,long_start)
b['geolocCountry'] = myGeolocCountry
**db.Docs.save(b)**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.