I wanted to know the top five largest collections in my MongoDB database in terms of document count. This JavaScript gets the job done.
// config var dbname = 'dev_bv'; var measure = 'count'; // or 'size' var numTopCollections = 5; function updateTopCollections(collection, stats, topCollections) { var thisCollectionObj = { 'name' : collection, 'count' : stats.count, 'size' : stats.size }; for(var i = 0; i < topCollections.length; i++){ if (stats[measure] > topCollections[i][measure]) { topCollections.splice(i, 0, thisCollectionObj); break; } } if (topCollections.length < numTopCollections) { topCollections.push(thisCollectionObj); } if (topCollections.length > numTopCollections) { topCollections.pop(); } } db = db.getSiblingDB(dbname); var collections = db.getCollectionNames(); var topCollections = []; for(var i = 0; i < collections.length; i++){ if (collections[i].match(/^system/)) { continue; } var stats = eval('db.' + collections[i] + '.stats()'); updateTopCollections(collections[i], stats, topCollections); } printjson (topCollections); |
Save it to a file, edit variables in the config section, and execute like so:
mongo --quiet topCollections.js |
Here’s a gist of same: https://gist.github.com/4150940