我正在执行一个查询,我只想知道集合中是否至少有一行与查询匹配,因此我将 limit=1
传递给 find()
。我所关心的是返回的游标的 count() 是否 > 0。使用 count(with_limit_and_skip=True)
还是仅使用 count()
会更快吗?直觉上我觉得我应该传递 with_limit_and_skip=True
,因为如果有一大堆匹配的记录,那么计数可能会停止在我的限制 1 处。
也许这值得解释一下限制和跳过在 mongodb/pymongo 中是如何工作的。
谢谢!
最佳答案
你的直觉是正确的。这就是 with_limit_and_skip
标志的全部意义。
使用 with_limit_and_skip=False
时,count()
必须计算所有匹配的文档,即使您使用 limit=1
也是如此几乎肯定会变慢。
来自docs :
Returns the number of documents in the results set for this query. Does not take limit() and skip() into account by default - set with_limit_and_skip to True if that is the desired behavior.
关于mongodb - 在 pymongo 中计算查询结果时使用 with_limit_and_skip=True 是否更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162595/