1

假设我们有以下内容。

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()

所以,我们已经保存了一个没有任何评论的帖子。每个帖子都是独一无二的

然后,我有一个 Comments 对象列表。我想做一个for循环以便一个一个地保存它们,或者创建一个评论对象列表并更新一次。

另外,我想检查其中一些 Comment 对象是否已经在 Post.comment 列表字段中。

我努力了

        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)

因此,这可行,但它会在不检查的情况下附加文档。因此,如果我多次运行它,我会得到重复。

任何想法 ?再次感谢。

4

1 回答 1

1

尝试使用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)

这 2 次更新会将comments1列表和comments2列表中的每个文档添加到一组中,因此comment2不会添加两次。

于 2016-12-12T11:47:38.083 回答