In MongoDB’s pymongo, how do I do a count()?

Since pymongo version 3.7.0 and above count() is deprecated. Instead use Collection.count_documents. Running cursor.count or collection.count will result in following warning message:

DeprecationWarning: count is deprecated. Use Collection.count_documents instead.

To use count_documents the code can be adjusted as follows

import pymongo

db = pymongo.MongoClient()
col = db[DATABASE][COLLECTION]

find = {"test_set":"abc"}
sort = [("abc",pymongo.DESCENDING)]
skip = 10
limit = 10

doc_count = col.count_documents(find, skip=skip)
results = col.find(find).sort(sort).skip(skip).limit(limit)

for doc in result:
   //Process Document

Note: count_documents method performs relatively slow as compared to count method. In order to optimize you can use collection.estimated_document_count. This method will return estimated number of docs(as the name suggested) based on collection metadata.

Leave a Comment