w3resource

Dropping a MongoDB Database from the Command Line

How to Drop a MongoDB Database from the Command Line?

To drop a MongoDB database from the command line, you can use the db.dropDatabase() command within the MongoDB shell. This command deletes the entire database, including all collections and data. Here’s how to do it, along with syntax, example code, and an explanation.

Description:

Dropping a MongoDB database from the command line is straightforward and can be done directly from the MongoDB shell. The command removes all collections, documents, and metadata for the database. Use this command with caution, as the action is irreversible.

Syntax:

The syntax for dropping a MongoDB database is:

db.dropDatabase()

This command must be run in the context of the database you want to delete.

Example Code:

In this example, we’ll drop a database named testdb from the MongoDB shell.

Code:

// Switch to the database 'testdb'
use testdb

// Drop the current database
db.dropDatabase()

Explanation:

  • use testdb
    The use command switches the context to the database you intend to drop, in this case, testdb.
  • db.dropDatabase()
    This command deletes the current database (in this case, testdb) and all of its contents. Once executed, this operation cannot be undone, so it should be used carefully.

After running this code, MongoDB will remove the testdb database entirely.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/snippets/dropping-a-mongodb-database-from-the-command-line.php