How to iterate over all MongoDB databases?

To iterate over all MongoDB databases, you need to switch to the admin database and use the listDatabases command. This returns information about all databases in the MongoDB instance.

Syntax

// Switch to admin database
switchDatabaseAdmin = db.getSiblingDB("admin");

// Get all database information
allDatabaseName = switchDatabaseAdmin.runCommand({ "listDatabases": 1 }).databases;

Example

Here's how to get information about all databases ?

switchDatabaseAdmin = db.getSiblingDB("admin");
allDatabaseName = switchDatabaseAdmin.runCommand({ "listDatabases": 1 }).databases;

This will produce the following output ?

[
    {
        "name" : "admin",
        "sizeOnDisk" : 495616,
        "empty" : false
    },
    {
        "name" : "config",
        "sizeOnDisk" : 98304,
        "empty" : false
    },
    {
        "name" : "local",
        "sizeOnDisk" : 73728,
        "empty" : false
    },
    {
        "name" : "sample",
        "sizeOnDisk" : 1335296,
        "empty" : false
    },
    {
        "name" : "sampleDemo",
        "sizeOnDisk" : 278528,
        "empty" : false
    },
    {
        "name" : "studentSearch",
        "sizeOnDisk" : 262144,
        "empty" : false
    },
    {
        "name" : "test",
        "sizeOnDisk" : 8724480,
        "empty" : false
    }
]

Iterate Through Database Names

To iterate over just the database names ?

allDatabaseName.forEach(function(database) {
    print("Database Name: " + database.name);
});
Database Name: admin
Database Name: config
Database Name: local
Database Name: sample
Database Name: sampleDemo
Database Name: studentSearch
Database Name: test

Key Points

  • The getSiblingDB("admin") method switches to the admin database without changing your current connection.
  • The listDatabases command returns an array containing information about all databases.
  • Each database object includes name, sizeOnDisk, and empty properties.

Conclusion

Use db.getSiblingDB("admin").runCommand({"listDatabases": 1}) to retrieve all database information. You can then iterate through the results to access individual database names and properties.

Updated on: 2026-03-15T00:28:59+05:30

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements