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 databases command
show databases
,provides a list of all the databases.
- Using adminCommand
db.adminCommand('listDatabases')
.This command returns a document containing the following fields:
- databases – An array of documents, one document for each database.Each of this document contains:
- name – The database name
- sizeOnDisk – Size of the database file in bytes
- empty – A boolean indicating whether the database is empty or not
- totalSize – Sum of all the sizeOnDisk fields
- ok – Determines the success of the command, a value of 1 indicates success
Alternatively, you can usedb.adminCommand( { listDatabases: 1 } )
- Using getMongo
db.getMongo().getDBNames()
,returns an array of all the available database names.
2. Conclusion
In this article we have seen different ways to list the databases in MongoDB.