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

Solution 1:

If you're using pymongo version 3.7.0 or higher, see this answer instead.


If you want results_count to ignore your limit():

results = db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num)
results_count = results.count()

for post in results:

If you want the results_count to be capped at your limit(), set applySkipLimit to True:

results = db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num)
results_count = results.count(True)

for post in results:

Solution 2:

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.

Solution 3:

Not sure why you want the count if you are already passing limit 'num'. Anyway if you want to assert, here is what you should do.

results = db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num)

results_count = results.count(True)

That will match results_count with num