Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Update all Documents in a Collection using PyMongo
Next article icon

MongoDB is a document-oriented NoSQL database that is a non-relational DB. MongoDB is a schema-free database that is based onBinary 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 usingcount() 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
frompymongoimportMongoClientClient=MongoClient()myclient=MongoClient('localhost',27017)my_database=myclient[&quotGFG&quot]my_collection=my_database[&quotStudent&quot]# number of documents in the collectionmydoc=my_collection.find().count()print(&quotThenumberofdocumentsincollection:&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
frompymongoimportMongoClientClient=MongoClient()myclient=MongoClient('localhost',27017)my_database=myclient[&quotGFG&quot]my_collection=my_database[&quotStudent&quot]# number of documents in the collectiontotal_count=my_collection.count_documents({})print(&quotTotalnumberofdocuments:&quot,total_count)

Output:

Total number of documents :  8

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp