Python 插入后如何更新 Mongo 文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4372797/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:28:18  来源:igfitidea点击:

How do I update a Mongo document after inserting it?

pythonmongodbpymongodatabase

提问by TIMEX

Let's say I insert the document.

假设我插入了文档。

post = { some dictionary }
mongo_id = mycollection.insert(post)

Now, let's say I want to add a field and update it. How do I do that? This doesn't seem to work.....

现在,假设我想添加一个字段并更新它。我怎么做?这似乎不起作用......

post = mycollection.find_one({"_id":mongo_id}) 
post['newfield'] = "abc"
mycollection.save(post)

采纳答案by allait

In pymongo you can update with:
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
Upsert parameter will insert instead of updating if the post is not found in the database.
Documentation is available at mongodb site.

在 pymongo 中,您可以使用以下内容
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
进行更新:如果在数据库中找不到帖子,则 Upsert 参数将插入而不是更新。
文档可在mongodb 站点获得

UPDATEFor version > 3 use update_oneinstead of update:

UPDATE对于版本 > 3 使用update_one而不是update

mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)

mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)

回答by Andrew_1510

I will use collection.save(the_changed_dict)this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.:

我会用collection.save(the_changed_dict)这种方式。我刚刚测试了这个,它仍然对我有用。以下内容直接引自pymongo doc.

save(to_save[, manipulate=True[, safe=False[, **kwargs]]])

save(to_save[, manipulate=True[, safe=False[, **kwargs]]])

Save a document in this collection.

If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.

在此集合中保存文档。

如果 to_save 已具有“_id”,则执行 update()(更新插入)操作,并覆盖具有该“_id”的任何现有文档。否则执行 insert() 操作。在这种情况下,如果操作为 True,一个“_id”将被添加到 to_save 并且此方法返回已保存文档的“_id”。如果操作为 False,服务器将添加“_id”,但此方法将返回 None。

回答by ThinkBonobo

This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.

这是一个老问题,但我在寻找答案时偶然发现了这个问题,所以我想更新答案以供参考。

The methods saveand updateare deprecated.

方法saveupdate已弃用。

save(to_save, manipulate=True, check_keys=True, **kwargs)? Save a document in this collection.

DEPRECATED - Use insert_one() or replace_one() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

update(spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs) Update a document(s) in this collection.

DEPRECATED - Use replace_one(), update_one(), or update_many() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

保存(to_save,操纵=真,check_keys=真,**kwargs)?在此集合中保存文档。

已弃用 - 请改用 insert_one() 或 replace_one()。

在 3.0 版更改: 删除了安全参数。为未确认的写操作传递 w=0。

更新(规范,文档,upsert=假,操作=假,多=假,check_keys=真,**kwargs)更新这个集合中的一个或多个文档。

已弃用 - 改用 replace_one()、update_one() 或 update_many()。

在 3.0 版更改: 删除了安全参数。为未确认的写操作传递 w=0。

in the OPs particular case, it's better to use replace_one.

在 OP 的特殊情况下,最好使用replace_one.

回答by Gürol Canbek

According to the latest documentation about PyMongo titled Insert a Document(insert is deprecated) and following defensive approach, you should insert and update as follows:

根据名为Insert a Document(insert is deprecated) 和以下防御性方法的有关 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)

回答by serv-inc

mycollection.find_one_and_update({"_id": mongo_id}, 
                                 {"$set": {"newfield": "abc"}})

should work splendidly for you. If there is no document of id mongo_id, it will fail, unless you also use upsert=True. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER. All parameters are described in the API.

应该非常适合你。如果没有 id 的文档mongo_id,它将失败,除非您也使用upsert=True. 这默认返回旧文档。要获得新的,请通过return_document=ReturnDocument.AFTERAPI中描述了所有参数。

The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.

该方法是为 MongoDB 3.0 引入的。它被扩展为 3.2、3.4 和 3.6。