Iterate over all Mongo database

前端 未结 1 1926
被撕碎了的回忆
被撕碎了的回忆 2021-02-01 07:17

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 comman

相关标签:
1条回答
  • 2021-02-01 07:54

    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);
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题