w3resource

Delete all data in a MongoDB Database with dropDatabase()

How to delete all data in a MongoDB Database?

To delete all data in a MongoDB database, you can use the db.dropDatabase() command. This command removes the entire database, including all collections, indexes, and documents within it. It's a quick way to clear out all data when you no longer need the database or want a fresh start.

In MongoDB, deleting everything in a database is done with the db.dropDatabase() command. This command is efficient for removing all collections, documents, and indexes in a single action. Be cautious when using this command, as it is irreversible and will permanently delete all data in the specified database. Use it when you’re sure you want to remove all stored data, such as during development or when resetting data.

Syntax:

The syntax to delete everything in a MongoDB database is:

db.dropDatabase()

Explanation:

  • db: Represents the current database you are connected to.
  • .dropDatabase(): Command that deletes the entire database.

Example:

Here's an example that demonstrates how to delete all data in a database named myDatabase.

Switch to the Target Database:

Code:

// Use the target database
use myDatabase

Delete Everything in the Database:

Code:

// Delete all data in the current database
db.dropDatabase()

Explanation:

  • use myDatabase
    This command switches to the database you want to delete (in this case, myDatabase). It’s essential to ensure you’re in the correct database to avoid deleting unintended data.
  • db.dropDatabase()
    This command removes the entire myDatabase database, including all collections, documents, and indexes within it. After execution, myDatabase will no longer exist in MongoDB.

Note: This command is irreversible and will delete all data permanently. Use it carefully, especially in production environments, as MongoDB does not ask for confirmation when dropping a database.

This approach is commonly used for resetting data during development or testing, allowing for a clean, empty database to work with.

Practical Guides to MongoDB Snippets and Examples.



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://w3resource.com/mongodb/snippets/how-to-delete-all-data-in-a-mongodb-database.php