Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Created March 31, 2020 06:48
Show Gist options
  • Save jeanlescure/339aa689bd00ce78d8d984fe16c69ebc to your computer and use it in GitHub Desktop.
Save jeanlescure/339aa689bd00ce78d8d984fe16c69ebc to your computer and use it in GitHub Desktop.
// Get all databases
var dbNames = db.adminCommand( { listDatabases: 1 } ).databases.map(function(dbObj) {
  return dbObj.name;
});

// Size functions
var reduceSize = function(values) {
  return Array.sum(values);
};
var getNSize = function(collection, n) {
  return ((collection.count() - n) > 0) ? reduceSize(collection.find().skip(collection.count() - n).map(Object.bsonsize)) : -1;
};

// For each database...
dbNames.map(function(dbName) {
  try {
    // ...get instance...
    var dbIns = db.getSiblingDB(dbName);
    
    // ...then get size sets for each collection
    return {
      "db": dbName,
      "results": [
        dbIns.getCollectionNames().map(function(collName) {
          var collection = dbIns.getCollection(collName);
          
          var lastItemSize = getNSize(collection, 1);
          var lastTenItemSize = getNSize(collection, 10);
          var lastHundredItemSize = getNSize(collection, 100);
          var lastThousandItemSize = getNSize(collection, 1000);
          
          return {
            "collection": collName,
            "lastItemSize": lastItemSize,
            "lastTenItemSize": lastTenItemSize,
            "lastHundredItemSize": lastHundredItemSize,
            "lastThousandItemSize": lastThousandItemSize
          };
        })
      ]
    };
  } catch(e) {
    return {
      "db": dbName,
      "error": e
    };
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment