pymongo 查询特定条件的前1w笔数据,count结果为整个collection的记录数,我哪里错了?

新手上路,请多包涵

代码如下:
recode1 = table_out.find({}).sort([("_id",1)]).limit(10000)
print('总数:', recode1.count())
直接理解print出的count()数应该是10000,但是目前输出的是整个collection全部的记录数126w,烦请各位解答,非常感谢。

阅读 4.5k
1 个回答

mongo 的 cursor.count() 方法在默认情况下, 会忽略 cursor.skip()cursor.limit() 的效果, 而直接返回 find() 方法的匹配结果. 如果需要其考虑 limit, 则需要指定 applySkipLimit 参数为 true.
在 pymongo 中, 这个参数对应方法中的 with_limit_and_skip 参数. 懒得翻文档了, 以下是直接从 pymongo - cursor.py 源码中摘出来的函数定义:

def count(self, with_limit_and_skip=False):

具体到你的问题, 这么写就可以了:

recode1 = table_out.find({}).sort([("_id",1)]).limit(10000)
print('总数:', recode1.count(with_limit_and_skip=True))

参考: mongo 官方文档: cursor.count() :

applySkipLimit: boolean
Optional. Specifies whether to consider the effects of the cursor.skip() and cursor.limit() methods in the count. By default, the count() method ignores the effects of the cursor.skip() and cursor.limit(). Set applySkipLimit to true to consider the effect of these methods.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进