Get MongoDB Collection Size

January 1, 2018

As an administraor it is demanding to atleast managed your database and keep monitoring on the storage and you want to have a native script for a better performance.

Since MongoDB core is JavaScript and there are so many ways to achieve the result you want below are twop ways to so.

1

// Container class
function CollStats(name, storageSizeGB, indexSizeGB,SizeGB, totalSizeGB) {
  this.name = name;
  this.storageSizeGB = storageSizeGB.toFixed(0);
  this.indexSizeGB = indexSizeGB.toFixed(0);
  this.SizeGB = SizeGB.toFixed(0);
  this.totalSizeGB = totalSizeGB.toFixed(0);
}

CollStats.prototype.toString = function toStr() {
  var s = this.name + ', size = ' + this.SizeGB + ' MB, storage = ' + this.storageSizeGB + ' MB, index = ' +
          this.indexSizeGB + ' MB, total = ' + this.totalSizeGB + ' MB';
  return s;
}

var bytesInGB = 1024 * 1024 ;
var collectionNames = db.getCollectionNames();
var collStats = [];
for (i = 0; i < collectionNames.length; i++) {
  coll = collectionNames[i];
  s = db[coll].stats();
  var storageSizeGB = s['storageSize'] / bytesInGB;
  var indexSizeGB = s['totalIndexSize'] / bytesInGB;
  var SizeGB = s['size'] / bytesInGB;
  var totalSizeGB = storageSizeGB + indexSizeGB;
  var cs = new CollStats(s['ns'], storageSizeGB, indexSizeGB,SizeGB, totalSizeGB);
  collStats.push(cs);
}

// descending order sort
collStats.sort(function compare(a, b) {
  return b.totalSizeGB - a.totalSizeGB;
});

for (var i = 0; i < collStats.length; i++) {
  print(collStats[i]);
}

2

var collectionNames = db.getCollectionNames(), stats = [];
collectionNames.forEach(function (n) { stats.push(db[n].stats()); });
for (var c in stats) {
    size = Number(stats[c]['size'])
    totalIndexSize = Number(stats[c]['totalIndexSize'])
    var mtotalIndexSize = Math.round(totalIndexSize/1024/1024)
    var msize = Math.round(size/1024/1024)
    storagesize = Number(stats[c]['storageSize'])
    var mstoragesize = Math.round(storagesize/1024/1024)
    var mTotal = (msize + mstoragesize)
    print(new Date().toISOString().slice(0, 10) + ","
    + stats[c]['ns'] + " ,"
    + msize + " ,"
    + mstoragesize + " ,"
    + mtotalIndexSize + ","
    + mTotal
    );
}

I, Myself prefer the second method with the shell combined since it is shortend version.