鍍金池/ 問答/Python  數(shù)據(jù)庫/ pymongo 查詢特定條件的前1w筆數(shù)據(jù),count結(jié)果為整個collecti

pymongo 查詢特定條件的前1w筆數(shù)據(jù),count結(jié)果為整個collection的記錄數(shù),我哪里錯了?

代碼如下:
recode1 = table_out.find({}).sort([("_id",1)]).limit(10000)
print('總數(shù):', recode1.count())
直接理解print出的count()數(shù)應(yīng)該是10000,但是目前輸出的是整個collection全部的記錄數(shù)126w,煩請各位解答,非常感謝。

回答
編輯回答
爆扎

mongo 的 cursor.count() 方法在默認情況下, 會忽略 cursor.skip()cursor.limit() 的效果, 而直接返回 find() 方法的匹配結(jié)果. 如果需要其考慮 limit, 則需要指定 applySkipLimit 參數(shù)為 true.
在 pymongo 中, 這個參數(shù)對應(yīng)方法中的 with_limit_and_skip 參數(shù). 懶得翻文檔了, 以下是直接從 pymongo - cursor.py 源碼中摘出來的函數(shù)定義:

def count(self, with_limit_and_skip=False):

具體到你的問題, 這么寫就可以了:

recode1 = table_out.find({}).sort([("_id",1)]).limit(10000)
print('總數(shù):', 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.
2018年1月17日 16:13