MongoDB Delete Collection

In this post, We will learn How to delete a collection from MongoDB.

MongoDB shell command `db.collection.drop()` is used to drop the specified collection from the selected DB. Also, It will remove all the documents and indexes associated with the dropped collection.

Syntax:

db.collection_name.drop()
Drop Query Response:

It will return `true` when successfully drops a collection.
It will return `false` when collection to drop does not exist.

Create Collection:

First, We will create a topics3 collection in `learnmongodb` DB.

> use learnmongodb
switched to db learnmongodb
> 
db.createCollection('topics3')
{ "ok" : 1 }
> show collections
topics
topics2
topics3
>

Drop Collection:

Now we will drop `topics3` collection from MongoDB.

> db.topics3.drop()
true
> show collections
topics
topics2
>

Again check with the collection list, collection `topics3` is removed from selected MongoDB.

If there is no collection in a given name, It will return false.

> db.topics333.drop()
false
>

Complete Program:

> use learnmongodb
switched to db learnmongodb
> db.createCollection('topics3')
{ "ok" : 1 }
> show collections
topics
topics2
topics3
> db.topics3.drop()
true
> show collections
topics
topics2
> db.topics333.drop()
false
>

Key Points:

  • `drop()` will remove all the documents within the collection
  • `drop()` will remove any indexes associated with the collection
  • `drop()` will block other operations until it has completed
  • `drop()` will return TRUE or FALSE