How To Delete MongoDB Collections Using Python

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

When you need to delete a collection in MongoDB, it’s important to proceed with caution, because deleting is a permanent operation– the entire collection, and all of its documents, will be removed. Fortunately, it’s easy to delete collections in Python using the PyMongo driver. In this article, we’ll show two different methods that can be used to remove MongoDB collections in Python.

Prerequisites

Before we focus on the code needed to drop MongoDB collections in Python, let’s review the key system requirements for this task. There are a few important prerequisites to keep in mind:

  • First, the MongoDB client for Python needs to be installed. You can check to see the driver’s version with this command:
1
mongo --version
  • You’ll need to install the MongoDB driver for Python 3 using pip3 if you haven’t done so already:
1
pip3 install pymongo
  • You’ll need to have a collection available on the MongoDB server that you’re willing to delete in order to follow along with the examples in this tutorial. Be sure that the collection doesn’t have any important documents in it, since they will be deleted.

Get access to a MongoDB collection

Now that we’ve gone over the system requirements, we can turn our attention to the Python code. First, we’ll import the MongoClient class from the PyMongo library. We’ll use this class to create a new client that will connect to a MongoDB collection:

1
2
3
4
5
# import pymongo's MongoClient class
from pymongo import MongoClient

# create a new client instance of MongoClient
mongo_client = MongoClient('mongodb://localhost:27017')

Then, we’ll use our new MongoDB client instance to access a database and one of its collections:

1
2
db = mongo_client.some_database
col = db.some_collection

WARNING: Keep in mind that the commands in this article will permanently delete the specified collection and all of it documents on the MongoDB server. Only access a collection that you’re willing to part with.

Drop a MongoDB collection by calling its drop() method directly

Dropping a collection in MongoDB is very similar to deleting or removing; however, it’s more efficient because it removes the entire structure of the collection and its indexes instead of just removing a document or index one-by-one.

In this example, we use the collection object’s own db.collection.drop() method to drop a collection with PyMongo:

1
database_name.some_collection.drop()

NOTE: Note that the Collection class object’s drop() method does not return a results object to verify that the collection was dropped.

Verify the drop() method call was successful using the database object’slist_collection_names() method

You can verify that your collection was successfully dropped using the database object’s list_collection_names() method, which returns a Python list of all the collections in that particular database. If there are no collections in that database, the call will return an empty list object ([]):

Screenshot of Python IDLE accessing a MongoDB database and using the drop() method to remove a collection

To evaluate whether or not a collection is in a database, you can use Python’s in operator, which will return a True/False boolean value:

1
2
col_exists = 'Some Collection' in db.list_collection_names()
print ("'Some Collection' exists?", col_exists) # will print True or False

In the following example, we see how that boolean evaluation and the drop() method call would look if you put them together:

1
2
3
4
5
6
7
8
9
10
11
# check if a collection exists
col_exists = 'Some Collection' in db.list_collection_names()
print ("'Some Collection' exists:", col_exists) # will print True or False

# use the database_name.some_collection.drop() method call if True
if col_exists == True:
# get the collection object if it exists
col = db['Some Collection']

# drop the collection
col.drop()

The code shown above will call the collection object’s drop() method only after verifying that the collection actually exists.

The instance of the col Python object still exists even after the drop() method is called

While the drop() method deletes the collection and its documents on the server, it does not delete the instance of the collection object within the Python script. This means that the pymongo.collection.Collection object will still exist along with all of its attributes, but the actual collection and its documents in MongoDB will no longer exist:

Screenshot of Python's IDLE environment calling a PyMongo drop() method for a collection object instance

Given this knowledge, we could theoretically use the drop() call to wipe a collection clean, and then add more documents to it in the same script, which would have MongoDB re-create it.

Use MongoDB’s mongo Shell to verify that the collection has been dropped successfully

Another way to verify that the collection no longer exists is to use the Mongo shell.

To do this, open a new terminal window, and use the following code to display all of a MongoDB database’s collections:

1
2
3
mongo
use some_database
show collections

In the screenshot shown below, the MongoDB collection called new_collection2 should not be listed in the results returned from show collections because it was deleted.

Use the Mongo shell command show collections to verify that the collection was successfully dropped

Screenshot of using Python's IDLE to make an API call to a MongoDB database to drop a collection

Delete a MongoDB collection by calling the database object’s drop_collection() method

The drop_collection() method offers another simple way to delete MongoDB collections in Python, but this method call returns a dict object response, unlike the drop() method.

To use this method, we first access a database instance using the MongoDB client instance:

1
2
# access a database on a MongoDB server
db = mongo_client['Some-Database']

Then, we call that database object’s drop_collection() method and pass the collection name as a string:

1
response = db.drop_collection('Some Col')

The method returns a response object in the form of a Python dictionary. The keys of this API response will vary depending on whether or not the collection actually existed:

1
2
3
4
5
6
7
8
print ("\n", "drop_collection() response:", response)

# evaluate the dict object returned by API call
if 'errmsg' in response:
# e.g. 'ns not found'
print ("drop_collection() ERROR:", response['errmsg'])
elif 'ns' in response:
print ("the collection:", response['ns'], "is dropped.")

Have the drop_collection() method return a dict object

Screenshot of Python IDLE calling PyMongo drop_collection() method

Use the MongoDB Compass GUI to verify that the collection was dropped

If you have Mongo Compass installed, you can open the GUI application and use it to confirm that the specified collection was dropped.

The Compass GUI also offers an alternative way to drop a MongoDB collection if you don’t want to use the PyMongo driver in Python or the Mongo Shell.

Connect to the MongoDB server in Compass

After the GUI loads, click the green Connect button to connect to the local MongoDB server on your machine.

Screenshot of a MongoDB Compass GUI application with the green CONNECT button highlighted

Refresh the list of databases and collections in the Compass application

If you drop a collection while the Compass application was open and connected to MongoDB, you’ll need to perform a refresh in order to get an updated list of the remaining databases and collections on the cluster. Just click the small Refresh icon on the left-hand side of the application:

Screenshot of the MongoDB Compass GUI application opening a collection

The collection that was dropped using the Python script we looked at earlier will no longer be visible in the GUI application.

Drop a collection in the MongoDB Compass GUI

After refreshing the list of databases in the GUI, select one of them and use the dropdown to select a collection that you’d like to drop. To drop the collection, just click the trash can icon to the right of the collection name.

Compass will ask you to verify the name of the collection to drop by typing it into an input field. After you’ve entered the collection name correctly, the red DROP COLLECTION button will be enabled. If you click the button, the collection will be dropped:

Screenshot of MongoDB Compass GUI dropping a collection

Conclusion

When you need to delete a MongoDB collection, it’s important to work carefully, because dropping a collection also removes all the documents in the collection. Luckily, it’s easy to delete collections with PyMongo methods such as drop() and drop_collection(). Using the instructions provided in this tutorial, you’ll have no problem removing collections and their documents from your MongoDB database.

Throughout this article, we’ve looked at our Python code examples one section at a time. The code shown below includes the complete Python script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import the pymongo MongoClient class
from pymongo import MongoClient

# create a client instance
mongo_client = MongoClient('mongodb://localhost:27017')

# access a database on a MongoDB server
db = mongo_client['Some-Database']

# check if a collection exists
col_exists = 'Some Collection' in db.list_collection_names()
print ("'Some Collection' exists:", col_exists) # will print True or False

# use the database_name.some_collection.drop() method call
if col_exists == True:
# get the collection object if it exists
col = db['Some Collection']

# drop the collection
col.drop()

# call the drop_collection() method and return dict response
response = db.drop_collection('Some Col')

print ("\n", "drop_collection() response:", response)

# evaluate the dict object returned by API call
if 'errmsg' in response:
# e.g. 'ns not found'
print ("drop_collection() ERROR:", response['errmsg'])
elif 'ns' in response:
print ("the collection:", response['ns'], "is dropped.")

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.