Skip to main content

Common Commands in MongoDB

Check Size of Tables in a Database

To check the size of tables in a database, use the following command to access the desired database:

use database_name
  • Replace the database_name with the actual name of the database you want to access, for example: use mdworkflow.
function getReadableFileSizeString(fileSizeInBytes) {
var i = -1;
var byteUnits = [' kB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
do {
fileSizeInBytes = fileSizeInBytes / 1024;
i++;
} while (fileSizeInBytes > 1024);

return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};
var collectionNames = db.getCollectionNames(), stats = [];
collectionNames.forEach(function (n) {
var stat = db[n].stats();
var totalSize = stat.storageSize + stat.totalIndexSize;
stats.push({
ns: stat.ns,
count: stat.count,
totalSize: totalSize
});
});
stats = stats.sort(function(a, b) { return b['totalSize'] - a['totalSize']; });
for (var c in stats) {
print(stats[c]['ns'] + " , " + stats[c]['count'] + " , " + getReadableFileSizeString(stats[c]['totalSize']) + "");
}
  • After running the above command, it will display the size of tables in the current database.