Skip to content

Instantly share code, notes, and snippets.

@pingwping
Last active March 6, 2023 18:35
Show Gist options
  • Save pingwping/92219a8a1e9d44e1dd8a to your computer and use it in GitHub Desktop.
Save pingwping/92219a8a1e9d44e1dd8a to your computer and use it in GitHub Desktop.
Create and update embedded documents with MongoEngine
# 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)
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)
@Hercroce
Copy link

Hercroce commented Mar 6, 2023

If you have to update a list of fields based on a JSON or dictionary objects, you could also use the following:

update_comment = {content = "content update",
                  name = "name update"}

post = Post.objects.get(title="Quora rocks")
comment = post.comments.get(name="john")

for key in update:
    comment[key] = update_comment[key]

post.save()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment