mongodbcountpymongodatabase

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


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

How do I get the count()?


Solution

  • 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: