Skip to content

Instantly share code, notes, and snippets.

@robertusnegoro
Last active September 8, 2021 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertusnegoro/2919b0b6e0c341458f87140750c13e79 to your computer and use it in GitHub Desktop.
Save robertusnegoro/2919b0b6e0c341458f87140750c13e79 to your computer and use it in GitHub Desktop.
mongodb list all collection for a database and stats like storage size and chunk count
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];
};
function getStatsFor(dbs){
var dbstat = db.getSiblingDB(dbs);
var collectionNames = dbstat.getCollectionNames(), stats = [];
collectionNames.forEach(function (n) { stats.push(dbstat.getCollection(n).stats());});
stats = stats.sort(function(a, b) { return b['size'] - a['size']; });
for (var c in stats) {
print(
stats[c]['ns'] +","+
stats[c]['count'] +","+
stats[c]['nindexes'] +","+
getReadableFileSizeString(stats[c]['totalIndexSize']) +","+
getReadableFileSizeString(stats[c]['size']) +","+
stats[c]['nchunks'] +","+
getReadableFileSizeString(stats[c]['storageSize']) );
}
}
print("collectionName,documentCount,indexesCount,totalIndexSize,size,nChunkCount,storageSize");
getStatsFor('yourdatabasename')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment