0
0
MongodbHow-ToBeginner · 3 min read

How to Check Database Size in MongoDB Quickly

To check the size of a MongoDB database, use the db.stats() command in the MongoDB shell. This command returns detailed statistics including dataSize and storageSize, which show the size of the data and the storage used by the database.
📐

Syntax

The basic syntax to check the database size is:

  • db.stats(): Returns statistics about the current database including size details.
  • dataSize: The size of the data stored in the database in bytes.
  • storageSize: The total storage allocated for the database, which may be larger than dataSize due to preallocation and padding.
mongodb
db.stats()
💻

Example

This example shows how to get the size of the current database using db.stats(). It prints the data size and storage size in megabytes for easier reading.

javascript
const stats = db.stats();
print('Data Size (MB):', (stats.dataSize / (1024 * 1024)).toFixed(2));
print('Storage Size (MB):', (stats.storageSize / (1024 * 1024)).toFixed(2));
Output
Data Size (MB): 12.34 Storage Size (MB): 20.00
⚠️

Common Pitfalls

Some common mistakes when checking database size in MongoDB include:

  • Confusing dataSize with storageSize. storageSize can be larger due to preallocated space.
  • Not switching to the correct database before running db.stats(). Use use yourDatabaseName first.
  • Expecting db.stats() to show collection sizes; it shows database-wide stats. Use db.collection.stats() for collection size.
mongodb
/* Wrong: Running stats on wrong database */
use wrongDatabase
printjson(db.stats())

/* Right: Switch to correct database first */
use yourDatabaseName
printjson(db.stats())
📊

Quick Reference

Summary of commands to check database size in MongoDB:

CommandDescription
db.stats()Returns statistics about the current database including size info
db.collection.stats()Returns statistics about a specific collection including size
use yourDatabaseNameSwitch to the database you want to check
stats.dataSizeSize of data in bytes
stats.storageSizeTotal storage allocated in bytes

Key Takeaways

Use db.stats() to get the size of the current MongoDB database.
Remember to switch to the correct database with use yourDatabaseName before checking stats.
dataSize shows actual data size; storageSize includes allocated space.
For collection-specific size, use db.collection.stats().
Sizes are returned in bytes; convert to MB or GB for easier reading.