Count the number of Documents in MongoDB using Python

Mongodb is a document-oriented NoSQL database which is non-relational DB. Mongodb is a schema-free database which 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.

Syntax :



db.collection.count()

Example : Count the number of documents (my_data) in the collection using count().

Sample Database:

python-mongodb-sample-database4

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

Total number of documents :  8



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : soniyanagaraj30

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.