I have the following code in a collection:
class Author(Agent):
def foo(self):
self.find_another_document_and_update_it(ids)
self.processed = True
self.save()
def find_another_document_and_update_it(self, ids):
for id in ids:
documentA = Authors.objects(id=id)
documentA.update(inc__mentions=1)
Inside find_another_document_and_update_it() I query the database and retrieve a document A. and then I increment a counter in A. Then in foo(), after calling find_another_document_and_update_it(), I also save the current document lets say B. The problem is that although I can see that the counter in A is actually increased when self.save() is called, document A is reset to its old value. I guess the problem is to do with a concurrency issue and how MongoDB deals with it. I appreciate your help.
In MongoEngine 0.5
saveonly updates fields that have changed – prior it saved the whole document, which would have meant the previous update infind_another_document_and_update_itwould have been overwritten. In general and as with all things python, its better to be explicit – so you might want to useupdateto update a document.You should be able to update all mentions with a single update:
Regardless, the best way to update would be to call the global updates after
self.save(). That way the mentions are only incremented after you’ve processed and saved any changes.