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

StackOverflow https://stackoverflow.com/questions/22176934

  •  03-06-2023
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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']
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top