What is the proper way to update a listfield of embedded documents in mongoengine?

自古美人都是妖i 提交于 2019-12-03 03:30:57

You could use an EmbeddedDocumentListField instead of a list of embedded documents. That way you get access to some handy methods like filter, create or update:

class Comment(EmbeddedDocument):
    created = DateTimeField()
    text = StringField()

class Post(Document):
    comments = EmbeddedDocumentListField(Comment)

    ...

    def add_or_replace_comment(self, comment):
        existing = self.comments.filter(created=comment.created)
        if existing.count() == 0:
             self.comments.create(comment)
        else:
             existing.update(comment)

(code not tested)

You need to find the index of the existing comment.

You can then overwrite the old comment with the new comment (where i is the index) eg:

post.comments[i] = new_comment

then just do a post.save() and mongoengine will convert that to a $set operation.

Alternatively, you could just write the $set eg:

Post.objects(pk=post.pk).update(set__comments__i=comment)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!