Skip to content

Instantly share code, notes, and snippets.

@matteofigus
Created February 6, 2014 12:29
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save matteofigus/8843247 to your computer and use it in GitHub Desktop.
Save matteofigus/8843247 to your computer and use it in GitHub Desktop.
A script to list all the collections and document count for a specific mongodb db
// Usage: mongo {Server without mongodb:// example 127.0.0.1:27017}/{DbName} [-u {Username}] [-p {Password}] < ./mongo-ls.js
var collections = db.getCollectionNames();
print('Collections inside the db:');
for(var i = 0; i < collections.length; i++){
var name = collections[i];
if(name.substr(0, 6) != 'system')
print(name + ' - ' + db[name].count() + ' records');
}
@AbhijatSaxena
Copy link

Use db.listCollections() instead of db.getCollectionNames(),
getCollectionNames() is deprecated

@UFawadKhan
Copy link

UFawadKhan commented Apr 23, 2020

A script to list all the collections and document count for all mongodb databases


var alldbs = db.getMongo().getDBNames();
for(var j = 0; j < alldbs.length; j++)
{
    var db = db.getSiblingDB(alldbs[j]);
    var collections = db.getCollectionNames();
    for(var i = 0; i < collections.length; i++){
      var name = collections[i];
      if(name.substr(0, 6) != 'system'){
          var c = db.getCollection(name).count() ;
          print(db + '  ' + name + '    ' + c );
      }
    }
}

@tardigradeus
Copy link

A compact way to list all Documents in all collections

db.getCollectionNames().forEach(coll => print(coll," ",db.getCollection(coll).count()))

@siyavashhamdi
Copy link

// The current database to use.
use("DB_NAME");

const collections = db.getCollectionNames().sort();

for (const collection of collections) {
  const count = db.getCollection(collection).count();

  console.log(`${collection}: ${count}`);
}

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