Introduction to MongoDB collection.drop() Method
In MongoDB, the drop()
method is used to delete a specified collection. This method takes one parameter which is the name of the collection to be deleted. Dropping a collection will completely remove it from the database, and it cannot be recovered.
Syntax
db.collection.drop()
Use cases
The drop()
method is mainly used in the following scenarios:
- To delete an entire collection
- To re-create a collection with the same name
- To free up storage space
It should be noted that the drop()
method cannot be undone once executed, so use it with caution.
Example
Suppose we have a database named test
, which contains a collection named mycollection
. Now, we want to delete this collection. We can follow these steps:
-
First, we need to connect to the
test
database:> use test switched to db test
-
Next, we can use the
drop()
method to delete themycollection
collection:> db.mycollection.drop() true
In the above command, the drop()
method returns true
indicating that the collection has been successfully deleted. If the collection does not exist, false
is returned.
Conclusion
In this introduction, we have learned the basic usage of the drop()
method in MongoDB. It should be noted that using this method will completely remove the entire collection, so please consider carefully before using it, and be sure to back up your data to prevent data loss.