为什么在mongoengine中更新ListField时这么慢?
Why is it so slow when update ListField in mongoengine?
当我用 mongoengine.Here 更新 ListField 时太慢了
class Post(Document):
_id = StringField()
txt = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
class Comment(EmbeddedDocument):
comment = StringField()
...
...
position = 3000
_id = 3
update_comment_str = "example"
#query
post_obj = Post.objects(_id=str(_id)).first()
#update
post_obj.comments[position].comment = update_comment_str
#save
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 技巧。
当我用 mongoengine.Here 更新 ListField 时太慢了
class Post(Document):
_id = StringField()
txt = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
class Comment(EmbeddedDocument):
comment = StringField()
...
...
position = 3000
_id = 3
update_comment_str = "example"
#query
post_obj = Post.objects(_id=str(_id)).first()
#update
post_obj.comments[position].comment = update_comment_str
#save
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 技巧。