2 Ways to Delete a Collection in MongoDB

If you no longer need a collection in MongoDB, you can delete it.

Actually, the term for deleting a collection is to drop the collection.

Either way, here are two ways to delete/drop a collection when using the mongo shell.

The db.collection.drop() Method

The db.collection.drop() method removes a collection or view from the database. It also removes any indexes associated with the dropped collection.

Syntax:

db.collection.drop(<options>)

Where collection is the name of the collection or view that you want to delete, and <options> is an optional write concern.

Example:

db.employees.drop()

Result:

true

That removes the employees collection (or view) from the database.

Write Concern

If you specify a write concern, the syntax looks like this:

db.collection.drop( { writeConcern: <document> } )

Where <document> is the write concern.

Here’s an example that specifies a write concern:

db.owners.drop( { writeConcern: { w: "majority" } } )

The db.collection.drop() method actually provides a wrapper around the drop command (listed below).

The drop Command

The drop command removes a collection from the database.

Syntax:

{ drop: <collection_name>, writeConcern: <document>, comment: <any> }

Where:

  • <collection_name> is the name of the collection.
  • writeConcern is an optional argument that specifies a document expressing the write concern of the drop command. Write concern describes the level of acknowledgment requested from MongoDB for write operations.
  • comment is an optional user-provided comment to attach to this command. A comment can be any valid BSON type (string, integer, object, array, etc).

Example:

db.runCommand( { drop: "products" } )

Result:

 { "nIndexesWas" : 1, "ns" : "PetHotel.products", "ok" : 1 } 

That dropped the products collection in the PetHotel database.