Zen Momentum
Zen Momentum

Reputation: 133

In MongoDB, how do I print all collection counts and indexes?

I need to verify data before migrating to another server and I want to make sure all documents and indexes and transferred properly. Is there a command and I run to do this?

Upvotes: 11

Views: 9223

Answers (2)

ctappy
ctappy

Reputation: 177

localhost:PRIMARY> db.getCollectionNames().forEach(k => print(db[k].count(), JSON.stringify(db[k].getIndexKeys()), db[k].getName()))

will do this via mongo cli

Upvotes: 6

David H. Bennett
David H. Bennett

Reputation: 1842

This script will output what you want:

db = db.getSiblingDB('admin');

var dbs = db.adminCommand('listDatabases');

dbs.databases.forEach(function(database){
  print("Database: " + database.name);
  print("-----");

  db = db.getSiblingDB(database.name);

  db.getCollectionNames().forEach(function(collection) {
    indexes = db[collection].getIndexes();
    print("Collection '" + collection + "' documents: " + db[collection].count());
    print("Indexes for " + collection + ":");
    printjson(indexes);
  });

  print("");

});

Upvotes: 7

Related Questions