Skip to content

Instantly share code, notes, and snippets.

@davidst
Last active June 26, 2017 16:01
Show Gist options
  • Save davidst/775acda0b8e5868013e3869953aa7b72 to your computer and use it in GitHub Desktop.
Save davidst/775acda0b8e5868013e3869953aa7b72 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 mongo = db.getMongo();
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function getCollectionStatsFor(dbName, sort) {
var db = mongo.getDB(dbName);
db.getCollectionNames()
.map(x => db.getCollection(x).stats())
.sort((a, b) => sort ? b.size - a.size : 0)
.map(x => ({ name: x.ns, size: bytesToSize(x.size), storageSize: bytesToSize(x.storageSize) }))
.forEach(x => print(`${x.name}: ${x.size} (${x.storageSize})`));
}
function getDatabasesStats(sortDatabases, sortCollections) {
mongo.getDBNames()
.map(x => mongo.getDB(x).stats())
.sort((a, b) => sortDatabases ? b.dataSize - a.dataSize : 0)
.map(x => ({ name: x.db, size: bytesToSize(x.dataSize), storageSize: bytesToSize(x.storageSize) }))
.forEach(x => {
print(`\n ${x.name}: ${x.size} (${x.storageSize})\n`);
getCollectionStatsFor(x.name, sortCollections);
});
}
getDatabasesStats()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment