PyMongo 4.3.3中Cursor.count()报AttributeError的解决办法咨询
解决PyMongo中Cursor无count()方法的问题
错误原因
PyMongo 3.7+ 废弃了Cursor.count()方法,4.0+版本彻底移除该方法,因此调用col.find().count()会触发AttributeError: 'Cursor' object has no attribute 'count'。
符合需求的解决方案
以下两种方法均无需升级PyMongo,且不会消耗原游标:
方案1:克隆游标后计数
通过Cursor.clone()复制游标,对克隆后的游标执行计数操作,原游标可正常后续迭代:
def temp(col): cursor = col.find() # 克隆游标,避免消耗原游标 cloned_cursor = cursor.clone() return len(list(cloned_cursor)) print(temp(collection))
注意:若游标对应数据量极大,克隆后转列表会占用较多内存,但原游标不受影响。
方案2:利用explain获取匹配总数
调用Cursor.explain("executionStats"),从返回结果中提取匹配的文档总数,全程不消耗游标:
def temp(col): cursor = col.find() explain_result = cursor.explain("executionStats") # 获取匹配查询条件的所有文档总数(不受limit/skip影响) return explain_result['executionStats']['totalMatched'] # 若需获取游标实际返回的数量(受limit/skip限制),替换为: # return explain_result['executionStats']['nReturned'] print(temp(collection))
内容的提问来源于stack exchange,提问作者Eagle
相关产品推荐
相关产品推荐

