Skip to content

Instantly share code, notes, and snippets.

@rashkur
Forked from joeyAghion/mongodb_collection_sizes.js
Last active October 7, 2016 16:20
Show Gist options
  • Save rashkur/3078eb5b53ed44a6db27b6edbc03ea59 to your computer and use it in GitHub Desktop.
Save rashkur/3078eb5b53ed44a6db27b6edbc03ea59 to your computer and use it in GitHub Desktop.
List mongodb collections in descending order of size. Helpful for finding largest collections. First number is "size," second is "storageSize."
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.getCollection(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']) + ")"); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment