MongoDB

MongoDB Show Databases Example

1. Introduction

MongoDB is a popular document-oriented NoSQL database developed by MongoDB Inc.

In this post, we are going to see different ways to list all the available databases. To give a foreword, a database in MongoDB is technically made up of different Collections.

Before we getting into how to list databases, let’s first see how to create a database in MongoDB.

We do not have any specific command to create a database in MongoDB. To switch database, use the below command from mongo shell: use jcgdb
 
By executing the above command, MongoDB switches to use the database ‘jcgdb’. Suppose that this database has not been created prior to execution of the above command. Even after executing this command, the database will not be created because MongoDB lazily creates a database when the first collection of the database being created.

For more information on creating a database, please check this post.

Now, let’s see different ways to list the databases in a running Mongo instance.

    • Using show dbs command

show dbs,provides a list of all the databases.

Using show dbs command to list databases
Using show dbs command to list databases

  • Using show databases command

show databases,provides a list of all the databases.

Using show databases to list all databases
Using show databases to list all databases

  • Using adminCommand

db.adminCommand('listDatabases').This command returns a document containing the following fields:

  1. databases – An array of documents, one document for each database.Each of this document contains:
    1. name – The database name
    2. sizeOnDisk – Size of the database file in bytes
    3. empty – A boolean indicating whether the database is empty or not
  2. totalSize – Sum of all the sizeOnDisk fields
  3. ok – Determines the success of the command, a value of 1 indicates success
    Alternatively, you can use db.adminCommand( { listDatabases: 1 } )

listDatabases1
listDatabases admin command to list the available databases

  • Using getMongo

db.getMongo().getDBNames(),returns an array of all the available database names.

getDBNames1
Listing all database names using getDBNames

2. Conclusion

In this article we have seen different ways to list the databases in MongoDB.

Nagendra Varma

BE graduate from Computer Science discipline. Quick learner and take in a zeal to learn new technologies. Broad experience in working on JavaEE applications in an agile environment with projects having critical deadlines. Expertise in developing WEB services.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button