Create and Drop MongoDB Database

Create a database

The below command is used to create or access a MongoDB database.

use <database-name>;

Replace <database-name> with the name you want to keep to your database. We will use the todo database throughout this course.

The above use command does not create anything until you insert the first record. Here is an example of an insert command. In this example, we are inserting a task into the tasks collection.

db.tasks.insertOne({
    name: "Learn Chapter 1",
});

The below command verifies the database creation. It returns names and sizes of all the databases.

show databases; // OR you can use the "show dbs" command

You will see some databases other than todo. They are created by default by MongoDB on installation and are used for user management and system purpose.

Drop a database

Run the following commands in the terminal below to drop a database.

  1. Select the database that you want to drop.
use <database-name>;

2. Drop the database

db.dropDatabase();

This command will remove all the collections and documents.

You may see the below error if you don’t have enough permission to drop a database.

MongoServerError: not authorized on todo to execute command { dropDatabase: 1, lsid: { id: UUID("1479ef4b-5e3f-42df-aaf8-93234469e6dc") }, $db: "todo" }