假设我插入文档。

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 代替 更新:

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”的任何现有文档。否则将执行插入()操作。在这种情况下,如果操纵为true,则将“ _id”添加到to_save,此方法将返回已保存文档的“ _id”。如果操作是错误的,则服务器将添加“ _id”,但此方法将无返回。

这是一个古老的问题,但是我在寻找答案时偶然发现了这一点,因此我想将其更新给答案以供参考。

方法 saveupdate 被弃用。

保存(to_save,manipulate = true,check_keys = true,** kwargs)¶在此集合中保存文档。

弃用 - 使用insert_one()或替换_one()。

更改为3.0版:删除了安全参数。通过W = 0,对于未经批评的写操作。

update(spec,document,upsert = false,manipulate = false,multi = false,check_keys = true,** kwargs)在此集合中更新文档。

弃用 - 使用repent_one(),update_one()或update_many()。

更改为3.0版:删除了安全参数。通过W = 0,对于未经批评的写操作。

在特殊情况下,最好使用 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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top