python + pymongo:如何从for循环在mongo中的现有文档上插入新字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15666169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python + pymongo: how to insert a new field on an existing document in mongo from a for loop
提问by otmezger
I'm using a for loop in python to loop over the result of a query with pymongo. Here is the code:
我在 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...
The question I have is, how can I insert the variable myGeolocCountryinto the non existing field geolocCountryon the existing document (b)?
我的问题是,如何将变量myGeolocCountry插入到geolocCountry现有文档 ( b)上的非现有字段中?
I tried with
我试过
b['geolocCountry'] = myGeolocCountry
but it didn't work at all, it does not even produce an error.
但它根本不起作用,它甚至不会产生错误。
Thanks
谢谢
采纳答案by MostafaR
You should execute an update query like this:
您应该像这样执行更新查询:
db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
回答by Wes
You have to use the function update()in order to update records in your collection.
您必须使用该函数update()来更新集合中的记录。
With update you can specify a query (just like you have above with collection.find()but also provide a second dict that defines how you want to update the documents found in the query.
something like:
通过更新,您可以指定一个查询(就像您在上面collection.find()所做的那样,但还提供了第二个 dict 来定义您希望如何更新在查询中找到的文档。例如:
db.Docs.update({"geolocCountry":{"$exists":False}}, {"$set": "geolocCountry": myGeolocCountry})
Check out the API for the rest of the arguments.
查看 API 以了解其余参数。
回答by Satys
you need to save the collection after update.
您需要在更新后保存集合。
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)**
回答by ToxicMender
For pymongo > 3
对于pymongo > 3
db.Doc.update_one({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
In case of multiple updates:
在多次更新的情况下:
db.Doc.update_many({"geolocCountry": {"$exists": False}}, {"$set": {"geolocCountry": myGeolocCountry}})
For pymongo < 3
对于pymongo < 3
above/previous answers are correct
以上/以前的答案是正确的
db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
In case of multiple updates:
在多次更新的情况下:
db.Doc.update({"geolocCountry": {"$exists": False}}, {"$set": {"geolocCountry": myGeolocCountry}})

