How to use dropDatabase() In MongoDB

In MongoDB, dropDatabase method is used to drop the currently selected database, it can delete all collections, indexed, and data. If you use this, you can’t reverse the data Make sure you have backed up your data before dropping a database.

Syntax:

db.dropDatabase()
  • db: current database connection.
  • dropDatabase(): method that drops (deletes) the currently selected database.

Example: Delete the Entire GFG Database

Query:

use gfg
db.dropDatabase()

Output:

The above query initially switches to the database named called “gfg” using the use command, and it executes the db.dropDatabase() method to drop (delete) the entire “gfg” database, including all its collections, indexes, and data.

How to Delete Everything in a MongoDB Database?

In MongoDB, Deleting everything in the database is the most preventive task. These operations are irreversible, and all data, collections, indexes, and even the database itself will be permanently deleted.

In this article, we’ll explore different approaches to deleting all data in a MongoDB database from deleting individual collections to dropping the entire database.

Similar Reads

How to Delete Everything in MongoDB Database

When it comes to MongoDB, deleting all data can be solved in several ways. Below are the approaches that can help us to delete everything in different ways as follows:...

1. Using dropDatabase()

In MongoDB, dropDatabase method is used to drop the currently selected database, it can delete all collections, indexed, and data. If you use this, you can’t reverse the data Make sure you have backed up your data before dropping a database....

2. Using drop()

In MongoDB, the drop method is used to delete a particular collection from the database. If you use this, you can’t reverse the data drop method permanently deletes the collection or index and its data....

3. Using deleteMany()

In the MongoDB, deleteMany method is used to delete multiple documents from the collection that match the given filter criteria. If you use this, you can’t reverse the data deleteMany method permanently deletes the documents from the collection....

Conclusion

Overall summary, the drop method is used to delete only collections. To drop the entire database you can use dropDatabase method. and deleteMany method does not automatically drop the collection. When you truly want to delete and remove the entire database and start new database then use the above methods, it cannot be can’t reverse the data....