MongoDB Delete Collection
MongoDB Delete Collection – In this MongoDB Tutorial, we shall learn to delete or drop a MongoDB Collection.
To delete a MongoDB Collection, use db.collection.drop() command. Following is a step by step guide :
Step 1: Select the database where your collection is, with USE command.
Step 2: Verify if the collection is present.
Step 3: Issue drop() command on the collection. Syntax of drop() command is provided below :
where <collection_name> is mandatory and is the name of MongoDB Collection to be deleted.
Step 4: If the Collection is deleted successfully then ‘true‘ is echoed back as acknowledgement, else ‘false’ would be echoed back.
Example 1 – Delete MongoDB Collection
Following is an example to delete MongoDB Collection calledcustomers from MongoDB Database namedtutorialkart .
Open Mongo Shell and follow the commands in sequence.
> use tutorialkart switched to db tutorialkart > show collections customers myNewCollection > db.customers.drop() true > show collections myNewCollection >
Following is the explanation for each mongodb command we executed above
- use tutorialkart switched to tutorialkart database.
- show collections listed the collections in the selected database.
- db.customers.drop() deleted (dropped) collection namedcustomers .
- show collections verifies that there is no more a collection calledcustomers .
Example 2 – Delete Collection [Negative Scenario]
In this example, we will try to delete a non-existing database. drop() method should return false.
> db.noCollection.drop() false
MongoDB acknowledges with a false, informing that dropping collection namednoCollection is failure.
In this MongoDB Tutorial – MongoDB Delete Collection, we have learnt to delete MongoDB Collection with examples.