如何使用Mongoclient更新单个文档的嵌入文档列表字段?

时间:2016-12-09 13:54:37

标签: mongodb python-3.5 mongoengine embedded-documents

假设我们有以下内容。

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

因此,我们已经保存了帖子而没有任何评论。每篇文章唯一

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

此外,我想检查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)

所以,这可行,但它附加文件没有检查。因此,如果我多次运行它,我会得到重复。

有什么想法吗?再次感谢。

1 个答案:

答案 0 :(得分: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)

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

相关问题