Thursday, October 2, 2025
HomeLanguagesCount the number of Documents in MongoDB using Python

Count the number of Documents in MongoDB using Python

MongoDB is a document-oriented NoSQL database that is a non-relational DB. MongoDB is a schema-free database that is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in MongoDB are schema-less. PyMongo is one of the MongoDB drivers or client libraries. Using the PyMongo module we can send requests and receive responses from

Count the number of Documents using Python

Method 1: Using count() The total number of documents present in the collection can be retrieved by using count() method. Deprecated in version 3.7. 

Syntax : 

db.collection.count()

Example : Count the number of documents (my_data) in the collection using count(). Sample Database: python-mongodb-sample-database4 

Python3




from pymongo import MongoClient
 
 
Client = MongoClient()
myclient = MongoClient('localhost', 27017)
 
my_database = myclient[& quot
                        GFG & quot
                        ]
my_collection = my_database[& quot
                             Student & quot
                             ]
 
# number of documents in the collection
mydoc = my_collection.find().count()
print(& quot
       The number of documents in collection : & quot
       , mydoc)


Output :

The number of documents in collection :  8

Method 2: count_documents() Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection.

Syntax :

db.collection.count_documents({query, option})

Example: Retrieves the documents present in the collection and the count of the documents using count_documents(). 

Python3




from pymongo import MongoClient
 
 
Client = MongoClient()
myclient = MongoClient('localhost', 27017)
 
my_database = myclient[& quot
                        GFG & quot
                        ]
my_collection = my_database[& quot
                             Student & quot
                             ]
 
# number of documents in the collection
total_count = my_collection.count_documents({})
print(& quot
       Total number of documents : & quot
       , total_count)


Output:

Total number of documents :  8
RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11926 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7079 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS