Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my current code.

How do I get the count() ?

like image 503
TIMEX Avatar asked Dec 11 '10 06:12

TIMEX


People also ask

How do you get count in Pymongo?

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().

How do I count data in MongoDB?

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.

How do I count the number of rows in MongoDB?

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.


2 Answers

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: 
like image 113
thirtydot Avatar answered Oct 04 '22 08:10

thirtydot


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.

like image 44
Sohaib Farooqi Avatar answered Oct 04 '22 08:10

Sohaib Farooqi