【发布时间】:2019-05-04 10:32:52
【问题描述】:
在 mongoengine 的官方文档中,它说从 0.8 开始,no_cache() 被添加到 mongoengine 中。它能给我们带来什么好处? no_cache 申请的典型场景是什么?
【问题讨论】:
标签: mongodb pymongo mongoengine
在 mongoengine 的官方文档中,它说从 0.8 开始,no_cache() 被添加到 mongoengine 中。它能给我们带来什么好处? no_cache 申请的典型场景是什么?
【问题讨论】:
标签: mongodb pymongo mongoengine
这里的 Mongoengine 维护者 - 默认情况下(和历史上),mongoengine 在您迭代查询集时缓存查询集的所有结果。如果您重新迭代相同的变量,这样做的好处是不会触发查询,但缺点是将所有内容都保存在内存中。即:
class User(Document):
pass
users = User.objects() # users is a queryset, it didn't hit the db yet
_ = [us for us in in users] # hits the db and caches all user instances in the users object
_ = [us for us in in users] # does not hit the db anymore, uses the users cached data
users = User.objects().no_cache()
_ = [us for us in in users] # hits the db and caches all user instances
_ = [us for us in in users] # hits the db again
使用缓存听起来是个好主意,但实际上你很少会迭代同一个查询集 2 次,如果你迭代非常大的集合,内存消耗可能会成为一个问题。
注意以后可能会改为默认使用no_cache版本
【讨论】: