In MongoDB, a collection is like a container where we store related data. It's similar to a table in a relational database. Each collection consists of documents and each document has its own data.
In MongoDB, dropping a collection refers to deleting a collection in our database. We would want to delete a particular collection for various reasons.
In this Answer, we will learn how to drop a collection using the drop()
method.
The syntax of drop()
method is as following:
db.collectionName.drop()
db
: It is the current database we are working with.
collectionName
: It is the name of the collection we want to delete.
The drop(
) method accepts an optional parameter which is a callback function.
drop(function(error, statusCollection){ //call back function body })
error
: If an error occurs while deletion of the collection then this error is stored in the variable error
.
statusCollection
: It tells us the status of our deletion. In case of successful deletion, its value is true
otherwise false
.
The following example will help us better understand how to delete a collection using the drop()
method. We have already created our database db
and made a collection users
in it. Write the command db.users.drop()
to delete the collection users
. Then write show collections
on the terminal to verify if the collection has been deleted.
Note: We can also try the following example with the drop()
method having a callback function as a parameter.
We can use the drop()
method to delete a collection in MongoDB. If we are concerned about the potential error in our code, we can use the drop()
method with a callback function as a parameter to deal with the error.
Free Resources