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.

use <database_name>

Step 2: Verify if the collection is present.

show collections

Step 3: Issue drop() command on the collection. Syntax of drop() command is provided below :

db.<collection_name>.drop()

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

  1. use tutorialkart  switched to tutorialkart database.
  2. show collections  listed the collections in the selected database.
  3. db.customers.drop()  deleted (dropped) collection namedcustomers .
  4. show collections  verifies that there is no more a collection calledcustomers .
ADVERTISEMENT

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.

Conclusion

In this MongoDB TutorialMongoDB Delete Collection, we have learnt to delete MongoDB Collection with examples.