Skip to content

Instantly share code, notes, and snippets.

@pingwping
Last active March 6, 2023 18:35

Revisions

  1. pingwping revised this gist Aug 20, 2014. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    # REF: http://www.quora.com/How-do-I-create-and-update-embedded-documents-with-MongoEngine

    class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)
  2. pingwping created this gist Aug 20, 2014.
    35 changes: 35 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)


    class Post(Document):
    title = StringField(max_length=120, required=True)
    author = StringField(required=True)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))


    # Create a post:
    post = Post(title="Quora rocks", author="Ross", tags=['tutorial', 'how-to'])
    post.save()

    # Find a post
    post = Post.objects.find(title="Quora rocks").first()

    # Create a new comment
    comment = Comment(content="Great post!", name="john")

    # Add to comments list and save
    post.comments.append(comment)
    post.save()

    # To editing existing comments you can use atomic updates[1] or simply change the comment and call post.save() (this will also do an atomic update).

    # Update a comment in place
    post = Post.objects.find(title="Quora rocks").first()
    post.comments[0].name = "John"
    post.save()

    # Or update with a set operation
    post = Post.objects.find(title="Quora rocks", comment__name="john").update(set__comment__S__name="John)