MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come eseguire un aggiornamento atomico su un EmbeddedDocument in un ListField in MongoEngine?

Puoi utilizzare l'operatore posizionale per aggiornare il documento incorporato abbinato.

Ecco un esempio dai test (https://github.com/MongoEngine/mongoengine/blob/master/tests/test_queryset.py#L313)

def test_update_using_positional_operator(self):
    """Ensure that the list fields can be updated using the positional
    operator."""

    class Comment(EmbeddedDocument):
        by = StringField()
        votes = IntField()

    class BlogPost(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)