1

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.

sergiuz
  • 5,353
  • 1
  • 35
  • 51
Giorgos Perakis
  • 153
  • 2
  • 12

1 Answers1

1

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.

sergiuz
  • 5,353
  • 1
  • 35
  • 51
  • Thanks a lot. It worked! . I think that we should use the **update** and not **update_one** method now, since we are updating a list of objects. We don't do a *for* loop with your way – Giorgos Perakis Dec 12 '16 at 13:20