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.
我会用这种方式。我刚测试过这个,它对我仍然有效。以下内容直接引自
pymongo doc.
:save(to_save[, manipulate=True[, safe=False[, **kwargs]]])
应该为你工作得很出色。如果没有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)
相关问题 更多 >
编程相关推荐