Skip to content

Instantly share code, notes, and snippets.

@termi
Created May 7, 2025 09:30
Show Gist options
  • Save termi/0819d4ea772ef9129d8b675558535ee5 to your computer and use it in GitHub Desktop.
Save termi/0819d4ea772ef9129d8b675558535ee5 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."
/* 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];
}
db.getCollectionNames()
.map(function (n) { return db[n] ? db[n].stats() : null })
.filter(function (a) {return a != null})
.sort(function (a, b) { return b['size'] - a['size'] })
.filter(stats => stats['count'] > 50).forEach(function(stats) {
print(stats['ns'] + ' (' + stats['count'] + '): ' + getReadableFileSizeString(stats['size']) + ' (' + getReadableFileSizeString(stats['storageSize']) + ')');
})
;
function n(n){var t=-1,e=[" kB"," MB"," GB"," TB","PB","EB","ZB","YB"];do{n/=1024,t++}while(n>1024);return Math.max(n,.1).toFixed(1)+e[t]}db.getCollectionNames().map(function(n){return db[n]?db[n].stats():null}).filter(function(n){return null!=n}).sort(function(n,t){return t.size-n.size}).filter(n=>n.count>50).forEach(function(t){print(t.ns+" ("+t.count+"): "+n(t.size)+" ("+n(t.storageSize)+")")});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment