如何在插入Mongo文档后更新它? [英] How do I update a Mongo document after inserting it?

查看:134
本文介绍了如何在插入Mongo文档后更新它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们插入文档。

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)


推荐答案

在pymongo中,您可以更新:

mycollection.update({'_ id':mongo_id},{$ set :post},upsert = False)

如果在数据库中找不到该帖子,则Upsert参数将插入而不是更新。

文档可在 mongodb网站

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.

这篇关于如何在插入Mongo文档后更新它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆