Search code examples
mongodbpython-3.5mongoengineembedded-documents

How to update an Embedded Document List Field for single document with Mongoclient?


Let's say we have the following.

class Post(Document):
    uid = StringField(required=True, unique=True)
    text = StringField(required=True
    comments = EmbeddedDocumentListField(Comment)

class Comment(EmbeddedDocument):
    comment_id = StringField(required=True)
    comment = StringField(required=True)
    datetime = DatetimeField()

So, we have already saved a Post without any comments. Each post is unique.

Then, I have a list of Comments objects. I want to do a for loop in order to save them one by one, or create a list of the comments objects and update once.

Also, I would like to check if some of these Comment objects are already in the Post.comment list field.

I have tried

        for comment in comments:

            o_comment = Comment()
            o_comment.id = comment.get('id')
            o_comment.comment = comment.get('comment')
            o_comment.datetime = datetime.now()
            Post.objects(uid = 'some_id').update_one(push__comments = o_comment)

So, this works but It appends the documents without checking. So if I run it many times I get duplicates.

Any idea ? Thanks again.


Solution

  • Try using update_one(add_to_set__comments = <list_of_comments>):

    comment1 = Comment(comment_id='1', comment='comment1', datetime=datetime.datetime.now())
    comment2 = Comment(comment_id='2', comment='comment2', datetime=datetime.datetime.now())
    comment3 = Comment(comment_id='3', comment='comment3', datetime=datetime.datetime.now())
    
    comments1=[comment1, comment2]
    comments2=[comment2, comment3]
    
    
    Post.objects(uid = post.uid).update_one(add_to_set__comments = comments1)    
    Post.objects(uid = post.uid).update_one(add_to_set__comments = comments2)
    

    These 2 updates, will add each docs from comments1 list and comments2 list in a set, therefore comment2 will no be added twice.