假设我插入了文档。
post = { some dictionary }
mongo_id = mycollection.insert(post)
现在,假设我想添加一个字段并更新它。我怎么做?这似乎不起作用......
post = mycollection.find_one({"_id":mongo_id})
post['newfield'] = "abc"
mycollection.save(post)
在 pymongo 中,您可以更新:
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
如果在数据库中找不到帖子,Upsert 参数将插入而不是更新。
文档可在mongodb 站点获得。
更新对于版本 > 3 使用update_one而不是update:
mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)
mycollection.find_one_and_update({"_id": mongo_id},
{"$set": {"newfield": "abc"}})
应该为您出色地工作。如果没有 id 的文档mongo_id
,它会失败,除非你也使用upsert=True
. 默认情况下,这将返回旧文档。要获得新的,请通过return_document=ReturnDocument.AFTER
. API中描述了所有参数。
该方法是为 MongoDB 3.0 引入的。它针对 3.2、3.4 和 3.6 进行了扩展。
我会用collection.save(the_changed_dict)
这种方式。我刚刚对此进行了测试,它仍然对我有用。以下内容直接引用自pymongo doc.
:
save(to_save[, manipulate=True[, safe=False[, **kwargs]]])
在此集合中保存一个文档。
如果 to_save 已经有一个“_id”,则执行 update() (upsert) 操作,并覆盖具有该“_id”的任何现有文档。否则执行 insert() 操作。在这种情况下,如果操作为真,则“_id”将添加到 to_save,并且此方法返回已保存文档的“_id”。如果操作为假,则服务器将添加“_id”,但此方法将返回无。
根据有关 PyMongo 的最新文档,标题为Insert a Document (insert is deprecated) 并遵循防御方法,您应该按如下方式插入和更新:
result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})
if post is not None:
post['newfield'] = "abc"
mycollection.save(post)
这是一个老问题,但我在寻找答案时偶然发现了这个问题,所以我想提供答案的更新以供参考。
方法save
和update
已弃用。
保存(to_save,操作=True,check_keys=True,**kwargs)¶ 在这个集合中保存一个文档。
已弃用 - 改用 insert_one() 或 replace_one()。
在 3.0 版更改: 删除了安全参数。为未确认的写操作传递 w=0。
update(spec, document, upsert=False, modify=False, multi=False, check_keys=True, **kwargs) 更新此集合中的文档。
已弃用 - 改用 replace_one()、update_one() 或 update_many()。
在 3.0 版更改: 删除了安全参数。为未确认的写操作传递 w=0。
在 OPs 的特殊情况下,最好使用replace_one
.