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.
You can use
db.getSiblingDB()
to switch between databases anddb.getCollectionNames()
to get the collection names. Note that you have to run the first command from theadmin
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: