MongoDB - Drop Collection
MongoDB - Dropping a Collection
Section titled “MongoDB - Dropping a Collection”In MongoDB, you can remove an entire collection from a database. This operation is permanent and also removes all documents and indexes associated with that collection.
The drop() Method
Section titled “The drop() Method”MongoDB’s db.collection.drop() method is used to drop a collection from the current database.
Syntax
Section titled “Syntax”The basic syntax for the drop() command is as follows:
db.COLLECTION_NAME.drop()Important Considerations
Section titled “Important Considerations”- Irreversible Operation: Dropping a collection is a destructive and permanent action. Once a collection is dropped, its data cannot be recovered without a backup.
- Index Removal: This command deletes all indexes associated with the collection, freeing up the storage space they occupied.
- Resource Locks: The
drop()method obtains an exclusive lock on the specified collection during its operation. Other operations on the collection will be blocked until the drop is complete.
Example
Section titled “Example”First, let’s switch to our database and see the available collections.
// Switch to the 'productDB' databaseuse productDB
// Show all collections in the current databaseshow collectionsThe output might look like this, showing we have a products collection and a temporary_data collection we want to remove.
productstemporary_dataNow, let’s drop the collection named temporary_data.
db.temporary_data.drop()If the operation is successful, MongoDB will return true.
trueLet’s check the list of collections again to confirm the removal.
show collectionsThe output now shows that temporary_data has been successfully dropped.
productsThe drop() method will return true if the selected collection was dropped successfully. If the collection does not exist, it will return false.