How do I tell if I inserted during upsert in mongoengine without (the deprecated) get_or_create?

蓝咒 提交于 2019-12-11 13:06:36

问题


I need to know if an upsert inserted, using MongoEngine (or if necessary, pymongo).

The code looks like this:

ret = MyMongoCollection.objects(name=desiredname)
            .update_one( { upsert: True, field1: 2 } )

Mongoengine seems to return only "num_affected" which is always exactly 1 here, by definition.

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

回答1:


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']



回答2:


I can't find a straight Mongoengine answer, but blending in PyMongo, the equivalent call is:

upsert_results = MyMongoCollection._get_collection().update(
    {
        'name':desiredName, 
        # NOTE: _cls (below) only necessary if you meta.allow_inheritance=True
        '_cls': MyMongoCollection._class_name 
    }, 
    {'$set': {'field1': 2}},
    upsert=True, multi=False)

obj_id = upsert_results.get('upserted',False) # key only exists if true.
obj_created = not upsert_results['updatedExisting']


来源:https://stackoverflow.com/questions/22176934/how-do-i-tell-if-i-inserted-during-upsert-in-mongoengine-without-the-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!