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

2024-04-19 17:59:11 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我插入了文档。

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

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

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

Tags: 文档iddictionarymongosavesomefindpost
3条回答

我会用这种方式。我刚测试过这个,它对我仍然有效。以下内容直接引自pymongo doc.

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.

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

应该为你工作得很出色。如果没有id为mongo_id的文档,它将失败,除非您还使用upsert=True。默认情况下,这将返回旧文档。要获得新的,请通过return_document=ReturnDocument.AFTER。所有参数都在the API中描述。

在MongoDB 3.0中介绍了该方法。扩展到3.2、3.4和3.6。

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

更新对于版本>;3,使用更新一个而不是更新

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

相关问题 更多 >