Altering an entire database in MongoDB is quite simple and can be performed in a variety of ways. Below we’ll briefly examine two methods for dropping (or deleting) a database in MongoDB, using both the *nix
shell as well as the Mongo shell utility.
Using the Unix Shell and Eval Command
The simplest method for deleting your Mongo database is to execute the mongo
shell command from the command line, along with the appropriate flags and options to inform the mongo
shell you wish to drop a database.
At the most basic level, the mongo
shell command can be used to quickly connect to a specific database. In this example, we’ll use it to connect to the bookstore
database from our server bash prompt:
$ mongo bookstore
MongoDB shell version: 3.0.9
connecting to: bookstore
>
However, rather than simply connecting to our bookstore
database and running commands from the mongo
shell, we can actually pass the eval
flag followed by the JavaScript code we wish MongoDB to execute, and our database can be easily dropped in one line.
In this case, we want to drop the database so we’ll then use the db.dropDatabase()
method to delete the database we’re connected to. While not necessary, we’ll also wrap this method in the printjson
function, to ensure the output of this command makes sense and is readable.
$ mongo bookstore --eval "printjson(db.dropDatabase())"
MongoDB shell version: 3.0.9
connecting to: bookstore
{ "dropped" : "bookstore", "ok" : 1 }
Using the Mongo Shell Utility
The alternative method begins by connecting to MongoDB through the mongo
shell utility, then issue commands within Mongo itself to connect to and drop the specific database.
While neither method is particularly advantageous over the other, in a production environment, it’s probably best to avoid using the above eval
option and instead use the mongo
shell as we’ll explore below, which allows you to ensure you’re connected to (and thus deleting) the proper database.
As before, begin by issuing the mongo
command from your bash shell:
$ mongo
MongoDB shell version: 3.0.9
connecting to: test
>
Now that you are connected to Mongo, use the show dbs
command to display all databases in the system:
> show dbs
local 0.078GB
bookstore 0.521GB
Now connect to the specific database that you wish to drop with the use <database>
command. In our case, we’ll once again connect to bookstore
:
> use bookstore
switched to db bookstore
Finally, execute the deletion by calling the db.dropDatabase()
method, similar to our eval
‘ed statement above.
> db.dropDatabase()
{ "dropped" : "bookstore", "ok" : 1 }
There you have it! Two simple methods for dropping a specific database from MongoDB quickly and easily.