Skip to content

Instantly share code, notes, and snippets.

@PofMagicfingers
Forked from ovntatar/readMongoDBSize.js
Last active June 30, 2024 14:23
Show Gist options
  • Save PofMagicfingers/f28edbd6f758e2c9aab8a4fa5ee7041d to your computer and use it in GitHub Desktop.
Save PofMagicfingers/f28edbd6f758e2c9aab8a4fa5ee7041d to your computer and use it in GitHub Desktop.
read human readable size from MongoDB collections
# inspired by https://gist.github.com/joeyAghion/6511184
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) { stats.push(db[n].stats()); });
stats = stats.sort(function(a, b) { return b['size'] - a['size']; });
for (var c in stats) {
print(stats[c]['ns'] + ": " + getReadableFileSizeString(stats[c]['size']) + " (" + getReadableFileSizeString(stats[c]['storageSize']) + ")" );
print(" - indexes : " + Object.keys(stats[c]['indexSizes']).map((k) => { return "\n\t" + k + " : " + getReadableFileSizeString(stats[c]['indexSizes'][k]); }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment