MacLochlainns Weblog

Michael McLaughlin's Technical Blog

Site Admin

Mongo List Databases

without comments

After you install MongoDB on your Linux system, you can connect without a user name or password and discover version and many other details about the installation, as shown in this prior post.

You can use the db.adminCommand() to understand the existing databases, as qualified in the online documentation. The basic syntax to list all databases is:

db.adminCommand( {listDatabases:1} )

In a generic Linux installation you should see something like the following:

{
        "databases" : [
                {
                        "name" : "admin",
                        "sizeOnDisk" : 32768,
                        "empty" : false
                },
                {
                        "name" : "config",
                        "sizeOnDisk" : 73728,
                        "empty" : false
                },
                {
                        "name" : "local",
                        "sizeOnDisk" : 90112,
                        "empty" : false
                },
                {
                        "name" : "test",
                        "sizeOnDisk" : 49152,
                        "empty" : false
                }
        ],
        "totalSize" : 245760,
        "ok" : 1
}

You can filter for a test database and find only your authorization to use the test database with the following command:

db.adminCommand( {listDatabases:1, filter: {"name": /test/}, authorizedDatabases: true} )

It returns:

{
        "databases" : [
                {
                        "name" : "test",
                        "sizeOnDisk" : 49152,
                        "empty" : false
                }
        ],
        "totalSize" : 49152,
        "ok" : 1
}

If you just want the names of your authorized databases, use this syntax:

db.adminCommand( {listDatabases:1, nameOnly: true, authorizedDatabases: true} )

It should return:

{
        "databases" : [
                {
                        "name" : "admin"
                },
                {
                        "name" : "config"
                },
                {
                        "name" : "local"
                },
                {
                        "name" : "test"
                }
        ],
        "ok" : 1
}

As always, I hope this helps those trying to sort through the official documentation and learn how to do things.

Written by maclochlainn

June 16th, 2021 at 11:09 pm

Posted in Linux,MongoDB

Tagged with ,