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() ?
Method 2: count_documents() Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection. Example: Retrieves the documents present in the collection and the count of the documents using count_documents().
Description. n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB connection. n = count( conn , collection ,'Query', mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.
count() method is used to return the count of documents that would match a find() query. The db. collection. count() method does not perform the find() operation but instead counts and returns the number of results that match a query.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With