Skip to content

Instantly share code, notes, and snippets.

@joeyAghion
Last active February 9, 2024 22:37
Show Gist options
  • Save joeyAghion/6511184 to your computer and use it in GitHub Desktop.
Save joeyAghion/6511184 to your computer and use it in GitHub Desktop.
List mongodb collections in descending order of size. Helpful for finding largest collections. First number is "size," second is "storageSize."
var collectionNames = db.getCollectionNames(), stats = [];
collectionNames.forEach(function (n) { stats.push(db[n].stats()); });
stats = stats.sort(function(a, b) { return b['size'] - a['size']; });
for (var c in stats) { print(stats[c]['ns'] + ": " + stats[c]['size'] + " (" + stats[c]['storageSize'] + ")"); }
@vishal3152
Copy link

vishal3152 commented Sep 23, 2020

Try this to get all DBs, collections and document count:

mongo --eval " db.getMongo().getDBNames().forEach( function(v, i){ db.getSiblingDB(v).getCollectionNames().forEach( function(vv, ii){ print (v + ',' + vv + ',' + db.getSiblingDB(v).getCollection(vv).count() ) } ) } ) "

@nenohweg
Copy link

nenohweg commented Jan 4, 2024

Is there a way to then store this data in a collection as historical data . To monitor collection size growth over a period of time

@dwinrick-lever
Copy link

@nenohweg something like datadog?

Also here's a version which works better for me - the versions at the top of this thread *** will silently omit values as they error on system.profile ***

(function() {
  const byteUnits = [" kB", " MB", " GB", " TB", "PB", "EB", "ZB", "YB"];

  // get collections by size sorted
  function getReadableFileSizeString(fileSizeInBytes) {
    let i = -1;
    do {
      fileSizeInBytes = fileSizeInBytes / 1024;
      i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
  }

  const collectionNames = db.getCollectionNames();
  let stats = [];
  for (const name of collectionNames) {
    if (name === 'system.profile') {
      continue;
    }
    stats.push(db.getCollection(name).stats());
  }
  stats = stats.sort(function(a, b) {
    return b["size"] - a["size"];
  });
  for (let i = 0; i < stats.length; i++) {
    console.log(stats[i]["ns"] + ": " + getReadableFileSizeString(stats[i]["size"]) + " (" + getReadableFileSizeString(stats[i]["storageSize"]) + ") - ", Number(stats[i].count).toLocaleString(), " docs");
  }
})();

Also includes formatted doc count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment