2 Ways to Delete a Database in MongoDB

If you no longer need a database in MongoDB you can delete it.

Technically speaking, the term normally used for deleting a database is drop. To drop a database is to delete it.

In any case, below are two ways you can drop/delete a database in the mongo shell.

The dropDatabase() Method

The db.dropDatabase() method is used specifically for dropping a database.

Specifically, it removes the current database, deleting the associated data files.

Example:

db.dropDatabase()

Result:

{ "dropped" : "krankykranes", "ok" : 1 }

That dropped the current database, which was called krankykranes.

The db.dropDatabase() method accepts an optional writeConcern argument in the form of a document expressing the write concern to use if greater than "majority".

The write concern, if specified, takes the following form:

{ w: <value>, j: <boolean>, wtimeout: <number> }

The db.dropDatabase() method is a wrapper for the dropDatabase administration command, which is explained below.

The dropDatabase Command

The dropDatabase administration command does exactly the same thing – it removes the current database, and deletes the associated data files.

Example:

db.runCommand( { dropDatabase: 1 } )

Result:

{ "dropped" : "krankykranes", "ok" : 1 }

Once again we dropped the krankykranes database.

The dropDatabase command also accepts a writeConcern field (in the same format as shown previously), as well as an optional comment field.

The syntax goes like this:

{ dropDatabase: 1, writeConcern: <document>, comment: <any> }

Delete Users

Both dropDatabase and db.dropDatabase() do not delete the users associated with the current database. To drop all associated users, run the dropAllUsersFromDatabase command in the database you are deleting.

Example:

db.runCommand( { dropAllUsersFromDatabase: 1 } )

Result:

{ "n" : NumberLong(3), "ok" : 1 }