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 :

  1. Select the database where your collection is, with USE command.
    use <database_name>
  2. Verify if the collection is present.
    show collections
  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.
  4. If the Collection is deleted successfully then ‘true‘ is echoed back as acknowledgement, else ‘false’ would be echoed back.

 

Example to 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.

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 .

 

Example – When you try to delete a non-existing collection

Following is an example to demonstrate the scenario – delete a non-existing database :

MongoDB acknowledges with a false, informing that dropping collection namednoCollection  is failure.

 

Conclusion :

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