How to Get Sorted List of Collection and Index Sizes in a MongoDB Database

If you have a large MongoDB database in production with a large of number of collections and indexes, you may need to periodically analyse the size of them. Here are a few MongoDB script snippets that you may find useful.

How to Get Sorted List of MongoDB Collections by Size?

The following script sorts and prints collections by descending order of the size of collections. The size here refers to the total size in memory for all records in a collection. This is different from the storage size of the collection. Note that the size printed is in kilobytes.

var sizeArray = [];

// Find statistics of every collection and add to an array
db.getCollectionNames().forEach(function(cName) {
    sizeArray.push(db[cName].stats());
});

// Sort the stats array by size. The field 'size' is used
sizeArray = sizeArray.sort(function(a, b) { return b['size'] - a['size']; });

// Print output in kb
for (var stat in sizeArray) {
    print(sizeArray[stat]['ns'] + ": " + (sizeArray[stat]['size']/1024).toFixed(2) + " kb") ;
}

Following is the sample output,

testdb.store: 3797.75 kb
testdb.customer: 526.26 kb
testdb.user: 0.52 kb

In the above snippet, change column from "size" to "storageSize" if you want to sort by storage size.

How to Get Sorted List of All MongoDB Indexes by Size in a Database?

The following program iterates through all indexes of all collections and then sorts it in the descending order of the size of the index.

var sizeMap = {}

// Iterate through every collection
db.getCollectionNames().forEach(function(cName) {
   indexes = db[cName].stats().indexSizes

   // Now iterate through every index of the current collection
   // We create a map here with key as combination of collection name and index name
   for (i in indexes) sizeMap[cName + " - " + i] = indexes[i];
});

var sizeArray = [];

// Map is converted to an array each element of which is a two member array
// This inner arrary contains the collection+index name key and the size itself
for (key in sizeMap) sizeArray.push([key, sizeMap[key]])

// Now sort outer array using the second column of inner array
var sizeArray = sizeArray.sort(function(a, b) {return b[1] - a[1]})

// Print list of index size in sorted form
for (x in sizeArray) print( sizeArray[x][0] + ": " + (sizeArray[x][1]/1024).toFixed(2) +" kb");

Following is a sample output,

store - country_1_city_1: 848.00 kb
store - _id_: 448.00 kb
customer - _id_: 96.00 kb
customer - age_1: 80.00 kb
user - _id_: 32.00 kb