How to Check MongoDB Size in Python?

Estimated read time 2 min read

To check the size of a MongoDB database or collection using Python, you can use the command method provided by the PyMongo library to execute the collStats command. Here’s an example:

from pymongo import MongoClient

# Establish a connection to MongoDB
client = MongoClient('mongodb://localhost:27017')

# Access the database and collection
db = client['your_database_name']
collection = db['your_collection_name']

# Check the size of a collection
collection_stats = db.command('collStats', 'your_collection_name')
collection_size = collection_stats['size']
print(f"The size of the collection is: {collection_size} bytes")

# Check the size of a database
db_stats = db.command('dbStats')
database_size = db_stats['dataSize']
print(f"The size of the database is: {database_size} bytes")

In the above code:

  1. First, you establish a connection to your MongoDB server using the MongoClient class. Make sure to provide the appropriate connection string.
  2. Next, you access the specific database and collection for which you want to check the size.
  3. To check the size of a collection, you use the db.command method and pass 'collStats' as the command along with the name of the collection. This command returns statistics for the specified collection, including the size in bytes.
  4. You can access the size field in the result to retrieve the size of the collection.
  5. To check the size of a database, you use the db.command method again, but this time you pass 'dbStats' as the command. This command returns statistics for the entire database, including the dataSize field representing the size in bytes.
  6. You can access the dataSize field in the result to retrieve the size of the database.

Make sure to replace 'your_database_name' and 'your_collection_name' with the actual names of your database and collection. Adjust the code accordingly if you want to check the size of a different collection or database.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply