MongoDB

MongoDB Delete Database From Command-Line

“In this post, we will break down how to drop a MongoDB database using the Mongo Shell interface. Learning how to use the MongoDB Shell is a powerful feature for any MongoDB user.”

Let’s dive in.

Login to MongoDB Server

The first step is to login into your MongoDB server. If you are on your local machine, ensure the MongoDB server is up and running.

Run the command:

$ mongosh

The command above should connect to your local Mongo server and drop you into an interactive shell.

Show Databases

The next step is to locate the database you wish to remove from the server. You can view all the databases in a server by running the command:

$ show databases

This command should output all the databases in the server and their corresponding disk size, as shown in the output below:

admin> show databases;

admin 40.00 KiB

config 48.00 KiB

customers 1.27 MiB

film 236.00 KiB

local 76.00 KiB

store 88.00 KiB

test 244.00 KiB

Switch to the Target Database

Once you have located the database you wish to remove, use the USE command to switch to that database.

For example, suppose we wish to remove the film database as shown in the output command; we can switch to that db with the command:

$ use film

The command will switch to the specified database allowing you to execute commands on that database,

Mongo Shell Delete Database Using the dropDatabase() Method

MongoDB provides us with the db.dropDatabase() command that allows you to drop an existing database from the server. Keep in mind that this command will remove the currently selected database; otherwise, the command will remove the default “test” database.

For example, to remove the film database, run the command:

film> db.dropDatabase()

{ ok: 1, dropped: 'film' }

The command will return the status and the name of the database removed.

Conclusion

Through this tutorial, you learned how to use Mongo Shell commands to remove an existing database from a MongoDB server.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list