Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chenyg0911/1c4626fbaaccbb3083fd7cc81418c401 to your computer and use it in GitHub Desktop.
Save chenyg0911/1c4626fbaaccbb3083fd7cc81418c401 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."
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'] + ": " + stats[c]['size'] + " (" + stats[c]['storageSize'] + ")");
}
@chenyg0911
Copy link
Author

chenyg0911 commented Jun 15, 2017

var mgo = new Mongo()

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(db){
    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']) + ")"); }
}

function getAllStats(){
    mgo.getDBNames().forEach(function(name){ var db = mgo.getDB(name); print('\n    '+db+'\n'); getStatsFor(db) })
}

getAllStats()

With these functions you can get stats for the current (use) DB with a simple getStatsFor(db) call, or get stats for a named DB with getStatsFor(mgo.getDB('db_name'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment