本文介绍了如何确定是否在monsengine的upsert过程中插入了没有get_or_create(不推荐使用)的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要知道是否使用MongoEngine(或必要时使用pymongo)插入了upsert.
I need to know if an upsert inserted, using MongoEngine (or if necessary, pymongo).
代码如下:
ret = MyMongoCollection.objects(name=desiredname)
.update_one( { upsert: True, field1: 2 } )
根据定义,Mongoengine似乎只返回"num_affected",此处始终始终为1.
Mongoengine seems to return only "num_affected" which is always exactly 1 here, by definition.
我知道它们存在,但是我正在寻找Python风格.
I know these exist, but I'm looking for the Python flavor.
- How to do "insert if not exist else update" with mongoengine?
- Check if MongoDB upsert did an insert or an update
推荐答案
这是另一个使用pymongo的答案,总是提供相关ID.上面的update()答案仅在字段为新字段时为您提供ID.
Here's another answer using pymongo that always provides the relevant ID. The update() answer above only gives you the ID if the field is new.
upsert_results = MyMongoCollection._get_collection().find_and_modify(
{
'name':desiredName,
# NOTE: _cls (below) only necessary if you meta.allow_inheritance=True
'_cls': MyMongoCollection._class_name
},
{'$set': {'field1': 2}}, # always provide a $set even if {} or it will no-op.
upsert=True, full_response=True, new=True, fields=['_id'])
obj_id = upsert_results['value']['_id']
obj_created = not upsert_results['lastErrorObject']['updatedExisting']
这篇关于如何确定是否在monsengine的upsert过程中插入了没有get_or_create(不推荐使用)的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!