Deleting a database in MongoDB can be achieved through various methods, with the most common approach being via the MongoDB command line interface. Below are the step-by-step instructions for deleting a MongoDB database using the command line:
-
Open the command line interface:
Launch the terminal or command prompt. -
Connect to the MongoDB instance:
If MongoDB is running locally, connect using the following command:bashmongoFor remote servers or specific ports, use:
bashmongo --host <hostname or IP> --port <port number> -
Select the target database:
Before deletion, select the database using theusecommand:bashuse <database name> -
Delete the database:
Execute thedb.dropDatabase()command to remove the selected database and all its data:bashdb.dropDatabase()
For example, to delete a database named testdb, follow these commands:
bashmongo # Connect to MongoDB use testdb # Select the testdb database db.dropDatabase() # Delete the database
Always back up any critical data before executing deletion operations, as the db.dropDatabase() command permanently removes data with no recovery option. Exercise caution when performing such operations.