Skip to content Skip to sidebar Skip to footer

How To Do An Atomic Update On An Embeddeddocument In A Listfield In Mongoengine?

I've found some similar questions on StackOverflow, but nothing that addresses what I'm looking for, so any help would be appreciated. My models: class BlogPost(EmbeddedDocument):

Solution 1:

You can use the positional operator to update the matched embedded document.

Heres an example from the tests (https://github.com/MongoEngine/mongoengine/blob/master/tests/test_queryset.py#L313)

deftest_update_using_positional_operator(self):
    """Ensure that the list fields can be updated using the positional
    operator."""classComment(EmbeddedDocument):
        by = StringField()
        votes = IntField()

    classBlogPost(Document):
        title = StringField()
        comments = ListField(EmbeddedDocumentField(Comment))

    BlogPost.drop_collection()

    c1 = Comment(by="joe", votes=3)
    c2 = Comment(by="jane", votes=7)

    BlogPost(title="ABC", comments=[c1, c2]).save()

    BlogPost.objects(comments__by="jane").update(inc__comments__S__votes=1)

    post = BlogPost.objects.first()
    self.assertEquals(post.comments[1].by, 'jane')
    self.assertEquals(post.comments[1].votes, 8)

Post a Comment for "How To Do An Atomic Update On An Embeddeddocument In A Listfield In Mongoengine?"