Switching and Creating Databases in MongoDB: A Comprehensive Guide

Learn how to manage databases in MongoDB using the MongoDB Shell and MongoDB Compass. Discover the use command for switching between databases and the process of creating new databases. This guide will provide you with the necessary knowledge to effectively work with multiple databases in your MongoDB environment.



Switch or Create a New MongoDB Database

MongoDB is a popular NoSQL database that stores data in collections. You can create or switch databases using MongoDB Shell or MongoDB Compass.

Create or Switch Database in MongoDB Shell

Use the use command to connect to a database. If the database does not exist, MongoDB will create it.

Switch or Create Database

use humanResourceDB

MongoDB will switch to the new database, showing humanResourceDB> in the prompt. To view all databases, use the show dbs command.

List Databases

show dbs

The "humanResourceDB" will not appear until a collection is added. To delete a database, use the db.dropDatabase() method.

Delete Database

db.dropDatabase()

Ensure method names are case-sensitive (e.g., db.dropDatabase(), not db.dropdatabase()).

Create a Database Using MongoDB Compass

Open MongoDB Compass and connect to your MongoDB server. Click CREATE DATABASE at the top of the window to open the creation popup.

Create Database in Compass

Database Name: humanResourceDB
Collection Name: employees

Enter the database and collection names, then click Create Database to create the new database and collection.