Question

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.

Was it helpful?

Solution

In MongoEngine 0.5 save only updates fields that have changed - prior it saved the whole document, which would have meant the previous update in find_another_document_and_update_it would have been overwritten. In general and as with all things python, its better to be explicit - so you might want to use update to update a document.

You should be able to update all mentions with a single update:

Authors.objects(id__in=ids).update(inc__mentions=1)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top