Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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');
}
@Rakesh1409

This comment has been minimized.

Copy link

Rakesh1409 commented Aug 5, 2016

i would like get the top 10 collections based on count (i mean in desc order). Please let me know how to achieve this.
i tried $orderby and sort .no luck.

@markunsworth

This comment has been minimized.

Copy link

markunsworth commented Nov 10, 2016

@rakesh You would need to save the collection name and object count in a list first, then sort it and take the top 10.

@cashbit

This comment has been minimized.

Copy link

cashbit commented Dec 27, 2016

On RoboMongo, this scripts is not working.. this is the right version, with a little add-on, (lists only collections with more than 1000 docs.)

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() ;
      if (c > 1000) print(name + ' - ' + c + ' records');
  }
}
@AbhijatSaxena

This comment has been minimized.

Copy link

AbhijatSaxena commented Aug 5, 2017

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

@UFawadKhan

This comment has been minimized.

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 );
      }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.