Mongoengine中no_cache()对querySet的影响

Can*_*her 6 mongodb pymongo mongoengine

在mongoengine的官方文档中,它说从0.8开始,no_cache()被添加到mongoengine中。它能给我们带来什么好处呢?no_cache的典型应用场景是什么?

bag*_*ard 7

Mongoengine 维护者在这里 - 默认情况下(历史上),mongoengine 会在您迭代查询集时缓存查询集的所有结果。这样做的好处是,如果您重新迭代同一变量,则不会触发查询,但缺点是将所有内容都保留在内存中。IE:

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
Run Code Online (Sandbox Code Playgroud)

使用缓存听起来是个好主意,但实际上您很少会迭代同一个查询集 2 次,并且如果您迭代非常大的集合,内存消耗可能会成为问题。

请注意,将来可能会更改为no_cache默认使用的版本