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

TIMEX picture TIMEX · Dec 11, 2010 · Viewed 45.3k times · Source
for post in db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num):

This is my current code.

How do I get the count() ?

Answer

thirtydot picture thirtydot · Dec 11, 2010

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: