hoangvu68
hoangvu68

Reputation: 865

Updating an embedded document in mongoengine

I have a class in mongoengine

class Post(EmbeddedDocument):
        uid = StringField(required=True)
        text = StringField(required=True)
        value = StringField()

class Feed(Document):
        label = StringField(required=True)
        feed_url = StringField(required=True)
        posts = ListField(EmbeddedDocumentField(Post))

I am trying to update the Post EmbeddedDocument property name text from a certain "Parent" document. As a first step, I retrieve the Feed Document

model = Feed.objects(_id="....").first()

and then I want to update the property text of the embedded document "Post".

How can I achieve it with mongoengine?

Upvotes: 9

Views: 7039

Answers (3)

eriel marimon
eriel marimon

Reputation: 1380

Expanding on @hoangvu68's answer. Here is another example: https://gist.github.com/pingwping/92219a8a1e9d44e1dd8a

The format is:

MyModel.objects.find(<model-key> = <model-val>, <embedded-doc-key>__<embedded-doc-lookup-key>=<lookup-key-val>).update(set__<embedded-doc-key>__S__<embedded-doc-lookup-key> = <new-val>)

Note this can be split in 2 lines

doc = MyModel.objects.find(<model-key> = <model-val>, <embedded-doc-key>__<embedded-doc-lookup-key> = <lookup-key-val>)
doc.update(set__<embedded-doc-key>__S__<embedded-doc-lookup-key> = <new-val>)

Upvotes: 1

hoangvu68
hoangvu68

Reputation: 865

I resolved it :)

Feed.objects(_id="...", posts__text="findvalue").update(set__posts__S__value="updatevalue")

Upvotes: 9

jared
jared

Reputation: 5539

If I understand the question, I think something like this will work:

model = Feed.objects(_id="....").first()
for post in model.posts:
    if post.text == "title":
        post.value = "placeholder for real update"
model.save()

Upvotes: 0

Related Questions