Create a gist now

Instantly share code, notes, and snippets.

List largest MongoDB collections
// I wanted to know the top five largest collections in my MongoDB database in
// terms of document count. This MongoDB-specific JavaScript gets the job done.
//
// Edit variables in the config section, then execute like so:
//
// mongo --quiet topCollections.js
// config
var dbname = 'FIXME';
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment