TIM*_*MEX 76 python database mongodb pymongo
假设我插入了文档.
post = { some dictionary }
mongo_id = mycollection.insert(post)
Run Code Online (Sandbox Code Playgroud)
现在,假设我想添加一个字段并对其进行更新.我怎么做?这似乎不起作用.....
post = mycollection.find_one({"_id":mongo_id})
post['newfield'] = "abc"
mycollection.save(post)
Run Code Online (Sandbox Code Playgroud)
ser*_*inc 26
mycollection.find_one_and_update({"_id": mongo_id},
{"$set": {"newfield": "abc"}})
Run Code Online (Sandbox Code Playgroud)
应该为你工作出色.如果没有id文件mongo_id
,它将失败,除非你也使用upsert=True
.这默认返回旧文档.要获得新的,通过return_document=ReturnDocument.AFTER
.所有参数都在API中描述.
该方法是为MongoDB 3.0引入的.它扩展到3.2,3.4和3.6.
And*_*510 22
我会用collection.save(the_changed_dict)
这种方式.我刚测试了这个,它仍然适用于我.以下引用直接来自pymongo doc.
:
save(to_save[, manipulate=True[, safe=False[, **kwargs]]])
将文档保存在此集合中.
如果to_save已经有"_id",则执行update()(upsert)操作,并覆盖具有该"_id"的任何现有文档.否则执行insert()操作.在这种情况下,如果操作为True,则将"_id"添加到to_save,此方法将返回已保存文档的"_id".如果操作为False,则服务器将添加"_id",但此方法将返回None.
这是一个老问题,但我在寻找答案时偶然发现了这个问题,所以我想给出答案的更新以供参考.
方法save
和update
已弃用.
save(to_save,manipulate = True,check_keys = True,**kwargs)将文档保存在此集合中.
DEPRECATED - 使用insert_one()或replace_one()代替.
在3.0版中更改:删除了安全参数.对于未确认的写操作,传递w = 0.
update(spec,document,upsert = False,manipulate = False,multi = False,check_keys = True,**kwargs)更新此集合中的文档.
DEPRECATED - 改为使用replace_one(),update_one()或update_many().
在3.0版中更改:删除了安全参数.对于未确认的写操作,传递w = 0.
在OP特殊情况下,最好使用replace_one
.
根据有关PyMongo的最新文档标题为插入文档(插入已被弃用)和遵循防御方法,您应该插入并更新如下:
result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})
if post is not None:
post['newfield'] = "abc"
mycollection.save(post)
Run Code Online (Sandbox Code Playgroud)