Iterate over the entire Mongo database

I am relatively new to MongoDB and I could not find a solution for what I'm looking for.

I would like to iterate over all mongo databases and run some command for 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” a database in a forEach loop so that I can run a query on each database? I want to use something like use db.name inside the loop, but this does not work.

+12
mongodb mongodb-query mongo-shell
Apr 13 '15 at 15:50
source share
1 answer

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

 // 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); }); }); 
+29
Apr 13 '15 at 17:13
source share



All Articles