I want to add a element in a ListField.Here is my code:
class Post(Document):
_id = StringField()
txt = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
class Comment(EmbeddedDocument):
comment = StringField()
comment_id = StringField()
...
...
insert_id = "3000"
update_comment_str = "example"
#query
post_obj = Post.objects(_id=str(_id)).first()
#find the element's position and update
position = 0
for position,_ in enumerate(post_obj.comments):
if post_obj.comments[position].comment_id = insert_id:
break;
post_obj.comments.insert(position+1,Comment(comment_id=str(len(post_obj.comments)+1),comment=update_comment_str)
#save
post_obj.save()
It's slow because I fetch the whole document into python instance .Then I save document.How to optimize it?