How to Create/Delete a Database with MongoDB Shell

Last updated on October 2, 2021 A Goodman Loading... Post a comment

This short post demonstrates how to create and drop a MongoDB database by using the command line.

Creating a New Database

The “use [your database name]” command will create a new database if it doesn’t exist, otherwise, it will return the existing database.

1. Start the Mongo Shell by running the following command:

mongo 

If you’re on a Mac or a Ubuntu server, you may need to add “sudo”:

sudo mongo

And enter your password to continue:

2. Let’s say I want to create a database called “kindacode_example”:

use kindacode_example

Screenshot:

Removing a Database

The steps below show you how to delete a database.

1. Start the MongoDB shell by running:

mongo 
// Or
sudo mongo

2. Select the database you want to remove:

use kindacode_example

3. Drop the selected database:

db.dropDatabase()

After it is deleted, you will see:

{ "ok" : 1 }

Screenshot:

To make sure the desired database is now gone, run:

dbs

You will get a list of the remaining databases.

Further reading:

You can also check out our database topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like