How to operate on all databases from the MongoDB shell?

To operate on all databases from MongoDB shell, you can use listDatabases along with adminCommand(). This method retrieves comprehensive information about all databases in your MongoDB instance.

Syntax

var allDatabaseList = db.adminCommand('listDatabases');
printjson(allDatabaseList);

Example

First, check the current database with the db command −

db;
test

Now retrieve information about all databases using adminCommand()

var allDatabaseList = db.adminCommand('listDatabases');
printjson(allDatabaseList);
{
    "databases" : [
        {
            "name" : "admin",
            "sizeOnDisk" : 495616,
            "empty" : false
        },
        {
            "name" : "config",
            "sizeOnDisk" : 98304,
            "empty" : false
        },
        {
            "name" : "local",
            "sizeOnDisk" : 73728,
            "empty" : false
        },
        {
            "name" : "sample",
            "sizeOnDisk" : 1388544,
            "empty" : false
        },
        {
            "name" : "sampleDemo",
            "sizeOnDisk" : 278528,
            "empty" : false
        },
        {
            "name" : "studentSearch",
            "sizeOnDisk" : 262144,
            "empty" : false
        },
        {
            "name" : "test",
            "sizeOnDisk" : 9695232,
            "empty" : false
        }
    ],
    "totalSize" : 12292096,
    "ok" : 1
}

Key Points

  • The adminCommand('listDatabases') returns metadata for all databases including name, size, and empty status.
  • Use printjson() to display the results in readable JSON format.
  • The totalSize field shows the combined disk usage of all databases.

Conclusion

The adminCommand('listDatabases') method provides a comprehensive way to view all databases in your MongoDB instance. Use printjson() to format the output for better readability.

Updated on: 2026-03-15T00:32:12+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements