Iterate over all Mongo database

Bakul G picture Bakul G · Apr 13, 2015 · Viewed 10.6k times · Source

I'm relatively new to MongoDB and I've not been able to find a solution for what I'm looking for.

I would like to iterate over all mongo databases and run some command on each collection of each database. I can run the following command to get all db names:

db.runCommand( { listDatabases: 1 } ).databases.forEach(function (db) {
    print ("db=" + db.name);
});

But how do I "switch" database within forEach loop so I can run query against each database? I want to use something like use db.name within loop but that's not working.

Answer

Juan Carlos Farah picture Juan Carlos Farah · Apr 13, 2015

You can use db.getSiblingDB() to switch between databases and db.getCollectionNames() to get the collection names. Note that you have to run the first command from the admin database in order to get the list of databases. A short script in the shell to achieve what you want to do would look something like the following:

// Switch to admin database and get list of databases.
db = db.getSiblingDB("admin");
dbs = db.runCommand({ "listDatabases": 1 }).databases;

// Iterate through each database and get its collections.
dbs.forEach(function(database) {
    db = db.getSiblingDB(database.name);
    cols = db.getCollectionNames();

    // Iterate through each collection.
    cols.forEach(function(col) {

        // Do something with each collection.
        print(col);
    });

});