Switch or Create a new MongoDB Database

MongoDB is a document-oriented open-source NoSQL database. It is one of the most popular and widely used NoSQL databases. In this tutorial, you will learn how to create a new MongoDB databases, or switch to an existing one.

A database is a place where data is stored in an organized way. In MongoDB, databases are used to store collections. A single MongoDB server can have multiple databases and a single MongoDB database can have multiple collections.

You can use MongoDB Shell or MongoDB Compass to create a new database.

MongoDB provides the use <database-name command to connect with the database. If the specified database name does not exist then it creates it and set it as a current database.

For example, the following command switch to the "humanResouredb" database. If it does not exist then creates it.

Example: Switch or Create Database
use humanResourceDB

The following shows how to create or switch MongoDB database in MongoDB shell mongosh:

Create or Switch Database in MongoDB Shell

MongoDB will automatically switch to the newly created database. Notice that it promts to humanResourceDB> now.

To check all the databases, use the "show dbs" command, as shown below.

List Databases

As you can see above, the "admin", "config", and "local" are default databases. As of now, "humanResourceDB" is not visible. This is because there is no collection in it.

To delete a database, use the db.dropDatabase() method which deletes a current database.

Delete Database

Above, { ok: 1, dropped: 'humanResourcedb' } indicates that the database deleted successfully.

Note: Method names are case sensitive. So, executing db.dropdatabase() will throw an error.

Create Database using MongoDB Compass

You can create a new database using MongoDB Compass. For that, open Compass and connect with your local or remote database. Once it connects with the MongoDB server, click on the top "CREATE DATABASE" button which will open the popup window, as shown below.

MongoDB Compass - Create Database

Enter your database name and collection name and click Create Database. This will create a new database humanResourceDB with the new employees collection shown below.

MongoDB Compass - Collections

Thus, you can create a new database in MongoDB.