MongoEngine/mongoengine

Method document.save() cause unwanted insertion

kietheros opened this issue · 3 comments

Code snippet

item = Item.objects.get(id='650986353e3af2b866e7c29d')
item.name = 'new name'
time.sleep(10)
# While sleeping 10s, run a shell command to delete this item.
item.save()

Result: item.save() will insert a new item with id, name and lost other fields.
Could you tell me how to update a document ?

  • Only update fields which are changed
  • upsert=False (only update, not insert)

The way save() know if document is inserted already is by checking if that document has _id field.
In that case the query will only update the changed fields.
You can add force_insert operator to .save(force_insert=True)
But it depends on what you try to do.

@idoshr

save(force_insert=False, validate=True, clean=True, write_concern=None, cascade=None, cascade_kwargs=None, _refs=None, save_condition=None, signal_kwargs=None, **kwargs)

If the document already exists, it will be updated, otherwise it will be created. The internal query is db.collection.update({}, {}, {upsert: true}
force_insert – only try to create a new document, don’t allow updates of existing documents. The internal query is db.collection.insert()

I want to only update document, the internal query should be db.collection.update({}, {}, {upsert: false}. Method save() doesn't support to do this.

I found the solution
document.save(save_condition={})