DeprecationWarning: count is deprecated. Use Collection.count_documents instead

简介: 当我使用pymongo查询出对应的cursor(find出的document的迭代器),然后查看查询出数据的数量时使用如下代码:```pythondb = MongoClient(host='192.168.1.3', port=27017)# dbname为操作的数据库名称,collectionname为操作的集合名称

环境

python 3.7
mongodb v4.2.1
pymongo 3.9.0

问题

DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
print(cursor.count())

场景

当我使用pymongo查询出对应的cursor(find出的document的迭代器),然后查看查询出数据的数量时使用如下代码:

db = MongoClient(host='192.168.1.3', port=27017)
# dbname为操作的数据库名称,collectionname为操作的集合名称
coll = db.dbname.collectionname
cursor = coll.find({'status': '1'}).limit(10)
print(cursor.count())

然后会弹出警报:`DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
print(cursor.count())`

原因

这是由于mongodb现在迭代器数据的搜集Collection.count()方式已经被弃用,更高的版本不适用。已经使用Collection.count_documents来统计了。

尝试

当我使用如下代码时

cursor = coll.find({'status': '1'})
print(cursor.count_documents())

会出现错误:AttributeError: 'Cursor' object has no attribute 'count_documents',原来find后的对象并没有count_documents这个方法或者属性,正确的使用方法是这样的:

num = coll.count_documents({'status': '1'})
print(num)

思考

新的用法固然好用,查询与统计只需一个就解决了,但是想想我的需求我需要先查找出,判断是否有数据,来执行下一步操作。这样新的方法就不满足需求了,如果查找一次再用count_documents可能俩次查找统计的并不是同一批数据。这个怎么办,我又不想用count(看着警报不爽),曲线救国吧,我发现我条件查询的数据并不是很多(为什么我要强调不是很多呢,因为一旦将迭代器转化成list,就需要占据内存,不能过于大,我建议最好再1w条数据以内),那就将迭代器转化成list,这样不就可以用len来统计数量了。

实现

cursor = coll.find({'status': '1'}).limit(10)
# 迭代器只能遍历使用一次,最好将list定义到一个新的变量,以便重复使用
cursor_list = list(cursor)
# 查看是否有status为0的数据
if len(cursor_list) != 0:
    # 这里循环不能使用cursor,因为cursor迭代器在转化成list时已经使用,再次使用就没有东西迭代了
    for document in cursor_list:
        print(document)
目录
相关文章
|
5月前
|
数据处理 开发者 Python
【Python】已解决:ValueError: Length mismatch: Expected axis has 5 elements, new values have 4 elements
【Python】已解决:ValueError: Length mismatch: Expected axis has 5 elements, new values have 4 elements
328 9
|
5月前
|
开发者 Python
【Python】已解决:FutureWarning: The default value of regex will change from True to False in a future ver
【Python】已解决:FutureWarning: The default value of regex will change from True to False in a future ver
122 1
|
5月前
|
开发者 Python
【Python】已解决:TypeError: descriptor ‘index‘ for ‘list‘ objects doesn‘t apply to a ‘str‘ object
【Python】已解决:TypeError: descriptor ‘index‘ for ‘list‘ objects doesn‘t apply to a ‘str‘ object
136 0
|
6月前
(145) Table ‘./addon_collect_wukong_spider‘ is marked as crashed and should be repaired解决思路
(145) Table ‘./addon_collect_wukong_spider‘ is marked as crashed and should be repaired解决思路
26 0
|
Python
Python报错ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Python报错ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
1617 1
DeprecationWarning:current URL string parser is deprecated, and will be removed in a future version.
DeprecationWarning:current URL string parser is deprecated, and will be removed in a future version.
|
数据库
解决numpy.core._exceptions.UFuncTypeError: ufunc ‘add‘ did not contain a loop with signature matching
解决numpy.core._exceptions.UFuncTypeError: ufunc ‘add‘ did not contain a loop with signature matching
1146 0
解决numpy.core._exceptions.UFuncTypeError: ufunc ‘add‘ did not contain a loop with signature matching
Pandas报错AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects
Pandas报错AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects
|
缓存 数据可视化
'dict' object has no attribute '_txn_read_preference' && Sort exceeded memory limit of 10485760
'dict' object has no attribute '_txn_read_preference' && Sort exceeded memory limit of 10485760
212 0
|
Java 数据库连接 mybatis
A query was run and no Result Maps were found for the Mapped Statement
A query was run and no Result Maps were found for the Mapped Statement
223 0