Skip to content

Instantly share code, notes, and snippets.

@meonkeys
Created November 26, 2012 22:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save meonkeys/4150940 to your computer and use it in GitHub Desktop.
Save meonkeys/4150940 to your computer and use it in GitHub Desktop.
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