简体   繁体   中英

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?

我解决了:)

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

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

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>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM