As a developer or DBA working with MongoDB, knowing how to view available databases is an essential skill. This in-depth guide will teach you multiple methods to list MongoDB databases right from the shell.

We‘ll compare SQL vs. NoSQL, highlight use cases for listing DBs, best practices for structuring databases, and also understand what happens behind the scenes when you execute these commands.

Relational DBs vs. MongoDB – A Quick Comparison

Before we dive into MongoDB specifics, let‘s compare how databases work in SQL vs MongoDB:

SQL Databases

  • Relational structure with table joins
  • Predefined schemas
  • ACID transactions
  • Vertically scalable

MongoDB

  • Document model (BSON)
  • Dynamic schemas
  • Eventually consistent
  • Horizontally scalable

While SQL databases are better for complex transactions, MongoDB excels at handling large volumes of data without strict relational constraints between entities. Its flexible document structure also makes it ideal for modern applications with evolving data requirements.

Key MongoDB Terminology:

  • Database: Physical container for collections, analogous to an RDBMS database
  • Collection: Group of MongoDB documents, equivalent to RDBMS tables
  • Document: Set of key-value pairs, similar to RDBMS rows
  • BSON: Binary format used to store documents, JSON-like

Now let‘s see why you‘d need to list databases and explore the methods to do so.

When Do You Need to List MongoDB Databases?

As a developer or DBA, some common use cases where you‘d want to view available Mongo databases include:

  • Prototyping/Testing: Listing test databases created during application development.
  • Queries/Reporting: Fetching metadata for databases to generate reports.
  • Data Imports: Importing datasets from CSVs/JSON to new collections.
  • Maintenance: Database admin tasks like backups, scaling capacity etc.
  • Access Control: Granting/revoking user permissions on databases.
  • Performance: Database profiling to tune performance.
  • Migrations: Migrate data from RDBMS like MySQL to MongoDB.

Understanding the use case helps apply appropriate filters while listing databases.

Best Practices for Structuring MongoDB Databases

Like designing SQL schemas, effectively modeling database architecture in MongoDB also affects performance. Here are some key guidelines for organizing databases and collections:

  • Logically group collections into databases by business function rather than data types. For example, store all user/order data in a webstore database rather than creating separate databases for customers and orders.

  • Keep normalized data that needs joins in SQL. Embed related data directly in documents to leverage MongoDB‘s document model.

  • Shard databases that exceed storage limits of a single server into horizontal partitions for scalability.

  • Index appropriately to optimize query performance especially for large collections.

  • Set database user permissions for security and prevent accidental data loss.

Let‘s now get into the methods for listing databases.

List Available MongoDB Databases

The following sections describe various approaches to get databases on a MongoDB instance, from basic to more advanced queries.

Using the show dbs Command

The most straightforward way is the show dbs command that displays databases alongside size:

> show dbs 
admin     0.000GB  
config    0.000GB
local     0.000GB
products  0.001GB    
customers 0.003GB

Running show dbs invokes the listDatabases command behind the scenes which fetches the database metadata from the MongoDB catalog. This metadata is then formatted into a human-readable table output.

While show dbs is great for a quick overview, it has some limitations:

  1. Only non-empty databases are displayed
  2. Limited metadata – only database names and sizes shown

If you need to view more metadata or want to display all databases including empty ones, use other methods shown next.

Using db.adminCommand({listDatabases:1})

To get more comprehensive metadata for databases, use the listDatabases command:

db.adminCommand({listDatabases:1})

This prints complete information in JSON format:

{
    "databases" : [
       {"name" : "admin","sizeOnDisk":8388608 ,"empty":false},
      {"name" : "config","sizeOnDisk":8388608,"empty":false}, 
      {"name" : "local","sizeOnDisk":8320030,"empty":false},
      {"name" : "products","sizeOnDisk":7340033,"empty":false},
      {"name": "customers","sizeOnDisk":3884532,"empty":false}
    ],
    "totalSize": 27926969,   
    "ok": 1
}

As you can see, using listDatabases exposes more database properties like storage sizes, and if they are empty.

List Only Database Names

Include the nameOnly parameter to show only database names:

> db.adminCommand({listDatabases:1, nameOnly:true})
{
   "databases":[
      "admin",
      "config",
      "local",
      "products",
        "customers"
   ],
   "totalSize":27926969,
   "ok":1
}

List Only Non-Empty Databases

To exclude empty databases from results, filter on the empty flag:

db.adminCommand({listDatabases:1, filter:{empty:false}}) 

You can combine nameOnly and filter to get only non-empty database names.

List Only Authorized Databases

To view only databases you are authorized to access:

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

Setting authorizedDatabases to true displays only databases matching the user permissions configured at authentication layer in MongoDB. This protects against accidentally modifying unauthorized databases.

Use Regular Expressions to Filter Databases

Additionally, you can filter by database names using regular expressions:

// Contains test
db.adminCommand({listDatabases: 1, filter: {name: /test/}})

// Starts with test 
db.adminCommand({listDatabases: 1, filter: {name: /^test/}})   

// Ends with test
db.adminCommand({listDatabases: 1, filter: {name: /test$/}})   

Regular expressions give you more fine-grained filtering capabilities right from MongoDB shell.

Alternative Methods to Get MongoDB Databases

There are a couple of JavaScript alternatives to get database names:

Using db.getMongo().getDBNames()

> db.getMongo().getDBNames()
[ 
    "admin",
    "config",
    "local",
     "products",
   "customers"
]

Access the Database Names Property

> db.getSiblingDBNames() 
[ 
    "admin",
    "config",
    "local",
     "products",
   "customers"
]

So those are the main methods to list MongoDB databases. Next, we‘ll explore visualizing databases using MongoDB Compass.

Visually Analyze MongoDB Databases with Compass

MongoDB Compass provides a graphical view into your databases with features like:

  • Intuitive dashboard displaying database overview
  • View storage metrics like indexes, document count etc
  • Interactively filter, sort documents
  • Real-time server statistics monitoring
  • Query performance analysis
  • Visual query builder

Below you can see the Compass dashboard displaying the list of databases:

MongoDB Compass Database List

The sidebar shows available databases while the right pane shows in-depth metrics per database like number of collections, total size, index sizes and more. This helps visually identify storage distribution across databases.

You can also create and query collections, build aggregation pipelines and analyze queries for performance – all through Compass‘s intuitive GUI.

For developers/DBAs, Compass becomes an indispensable tool for efficiently managing databases beyond just listing them. Its visualization dashboards provide additional insight notpossible directly via the mongo shell.

Conclusion

In this extensive guide, you learned:

  • Various scenarios where listing MongoDB databases becomes essential
  • How SQL database architecture differs from MongoDB‘s document model
  • Best practices for structuring databases and collections
  • Using show dbs, listDatabases, and other commands to view MongoDB databases
  • Filtering/sorting databases by parameters like name, size, permissions etc.
  • How Compass enables visual analysis of your database landscape

Having these database listing skills in your toolkit enables easier debugging, monitoring and managing MongoDB deployments, especially as data volumes grow larger.

By mastering both CLI and GUI methods covered here, you can boost your database administrator productivity when working with MongoDB.

Similar Posts