Iterate over all Mongo database

只谈情不闲聊 提交于 2019-12-02 20:54:15

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);
    });

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!