Create and Drop MongoDB Database
Learn and practice commands to create and drop a MongoDB database.
We'll cover the following
Create a database
We can use the below command to create or access a MongoDB database.
use <database-name>;
We can replace <database-name>
with the name of our choice. We’ll use the todo
database throughout this course.
The use
command does not create anything until we insert the first record. Below is an example of the 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 the names and sizes of all the databases.
show databases; // OR you can use the "show dbs" command
We’ll observe some databases other than todo
. When we install MongoDb, it installs these databases by default, and uses it for user management and system purpose.
Next, we’ll try the above commands in the terminal.
Drop a database
We’ll run the following commands in the terminal below to drop a database:
-
Select the database that we want to drop.
use <database-name>;
-
Drop the database
db.dropDatabase();
This command removes all the collections and documents.
We can come across the below error if there is not 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" }
Q&A
Below are some questions to test your understanding of this lesson.
What’s the purpose of the use command?
How is a database created in MongoDB?
What is the command to drop a database?