【问题标题】:Update document from inside another document - mongoengine从另一个文档中更新文档 - mongoengine
【发布时间】:2012-03-11 09:40:07
【问题描述】:

我的集合中有以下代码:

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 如何处理它有关。感谢您的帮助。

【问题讨论】:

    标签: mongodb mongoengine


    【解决方案1】:

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

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

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

    无论如何,最好的更新方式是在self.save() 之后调用全局更新。这样,仅在您处理并保存任何更改后,提及次数才会增加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 2015-04-24
      • 2020-04-20
      相关资源
      最近更新 更多