How to drop a mongodb database from mongo shell and command line?

This tutorial guides you how to drop a mongodb database from both mongo shell and command line.

Drop mongodb database from mongo shell

The mongo shell provides helper method called db.dropDatabase() and it wraps the dropDatabase command, which can be used to drop current database and to delete the associated data files.

The following example shows how to switch to current database (tempdb) using use <database> command and then use db.dropDatabase() helper method to drop mongodb database from mongo shell.

> show databases;

Response
---------

admin        0.000GB
config       0.000GB
local        0.000GB
mydb         0.000GB
sneppets     0.000GB
tempdb       0.000GB
test         0.000GB

> use tempdb

Response
-----------
switched to db tempdb

> db.dropDatabase()

Response
----------
{ "dropped" : "tempdb", "ok" : 1 }

Drop mongodb database from command line

If you wanted to drop mongodb database from the command line or system prompt, then use the –eval option to mongo to pass the shell a JavaScript part like mongo <database> –eval “db.dropDatabase()”  i.e., from the command line , use mongo to evaluate JavaScript as shown below.

C:\Program Files\MongoDB\Server.0\bin> mongo tempdb --eval "db.dropDatabase()"

Response
----------------

MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/tempdb?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f42717ce-1090-4cc7-a391-a6f7befa78c1")
}
MongoDB server version: 4.0.6
{ "dropped" : "tempdb", "ok" : 1 }

Also SeeHow to fetch last n records from a collection in mongodb

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments