0

我在集合中有以下代码:

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)

在里面find_another_document_and_update_it()我查询数据库并检索一个文档 A。然后我在 A 中增加一个计数器。然后在foo()调用之后find_another_document_and_update_it(),我还保存当前文档让我们说 B。问题是虽然我可以看到 A 中的计数器是实际上在self.save()被调用时增加,文档 A 被重置为其旧值。我想问题与并发问题以及 MongoDB 如何处理它有关。我感谢您的帮助。

4

1 回答 1

1

在 MongoEngine 0.5save中,仅更新已更改的字段 - 在它保存整个文档之前,这意味着之前的更新find_another_document_and_update_it将被覆盖。一般来说,和所有 python 一样,最好是明确的 - 所以你可能想用它update来更新文档。

您应该能够通过一次更新来更新所有提及:

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

无论如何,最好的更新方式是在self.save(). 这样,只有在您处理并保存了任何更改后,提及才会增加。

于 2012-03-12T16:45:35.303 回答