Python 为什么在mongoengine中更新ListField时速度这么慢?

Python 为什么在mongoengine中更新ListField时速度这么慢?,python,mongodb,mongoengine,Python,Mongodb,Mongoengine,使用mongoengine更新列表字段时速度太慢 class Post(文档): _id=StringField() txt=StringField() 注释=列表字段(EmbeddedDocumentField(注释)) 类注释(嵌入文档): comment=StringField() ... ... 位置=3000 _id=3 更新\u comment\u str=“示例” #质疑 post_obj=post.objects(_id=str(_id)).first() #更新 post\u

使用mongoengine更新列表字段时速度太慢

class Post(文档):
_id=StringField()
txt=StringField()
注释=列表字段(EmbeddedDocumentField(注释))
类注释(嵌入文档):
comment=StringField()
...
...
位置=3000
_id=3
更新\u comment\u str=“示例”
#质疑
post_obj=post.objects(_id=str(_id)).first()
#更新
post\u obj.comments[位置].comment=更新\u comment\u str
#拯救
post_obj.save()
时间成本随着post_obj.comments长度的增加而增加。 如何优化它

Post.objects(id=str(_id)).update(**{"comments__{}__comment".format(position): update_comment_str})
在你的代码中

  • 您将整个文档提取到python实例中,该实例将在RAM中进行

  • 然后更新第3000条评论,这将在mongoengine中发挥一些魔力(标记更改的字段等等)

  • 然后保存文档

  • 在我的回答中,我向mongodb发送了更新指令,而不是将包含N条注释的整个文档提取到Python中,这将节省内存(RAM)和时间

    mongoengine/MongoDB支持索引支持更新,如

    set__comments__1000__comment="blabla"
    
    为了使用变量给出位置,我使用了python字典和kwargs技巧

    在你的代码中

  • 您将整个文档提取到python实例中,该实例将在RAM中进行

  • 然后更新第3000条评论,这将在mongoengine中发挥一些魔力(标记更改的字段等等)

  • 然后保存文档

  • 在我的回答中,我向mongodb发送了更新指令,而不是将包含N条注释的整个文档提取到Python中,这将节省内存(RAM)和时间

    mongoengine/MongoDB支持索引支持更新,如

    set__comments__1000__comment="blabla"
    

    为了使用变量给出位置,我使用了python字典和kwargs技巧

    您解决了我的问题。谢谢。但是代码应该添加“set\uuuuuu”:
    Post.objects(id=str(\u id)).update(**{“set\uuuuuu comments\uuuuuu}}注释。格式(位置):update\u comment\ustr}
    set将在mongoengine中自动添加。您解决了我的问题。谢谢。但是代码应该添加“set\uuuuuuuuu”:
    Post.objects(id=str(\uid)).update(**{“设置注释集”。格式(位置):更新注释集将自动添加到mongoengine中。