How To Delete a MongoDB Database Using Python

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

Introduction

When you need to delete a database in MongoDB, it’s wise to proceed with caution, since deletion is permanent. Fortunately, it’s easy to remove a MongoDB database in Python with the help of the PyMongo driver. In this article, we’ll explain how to drop a MongoDB database in Python using the drop_database() method.

Prerequisites

Let’s review some of the key system requirements for this task before we turn our attention to the Python code. Here are a few prerequisites to keep in mind:

  • You’ll need to make sure that the MongoDB server is running on the same cluster as the node or machine where your Python script is running:
1
mongo --version
  • You’ll also need to install the PyMongo driver for MongoDB using pip3 with Python 3:
1
pip3 install pymongo
  • You’ll need to have a database on the MongoDB cluster that you can use to follow along with the code examples in this article. It’s recommended that you create a “throwaway” database for this exercise, and be sure to carefully input the database name before making any API calls, to avoid deleting anything by mistake.

Connect to MongoDB using the Compass GUI application

If you already have the MongoDB Compass GUI installed, you can use this application to verify that the API calls to MongoDB in Python were successful. Open the application and click the green Connect button to establish a connection with the MongoDB server:

Screenshot of the MongoDB Compass GUI application connecting to a server

Use the MongoDB Compass GUI to create a throwaway database for testing PyMongo API calls

You can also use MongoDB’s Compass application to create a “throwaway” database. To do this, just click the gray “+” icon at the bottom of the application to create a new database.

Keep in mind that database names, unlike collections, are not allowed to contain spaces— only hyphens (-), dashes (), and underscores (_) are permitted in the database name.

Screenshot of MongoDB Compass GUI displaying an error from user creating a database with a space in the name

Access the MongoClient class and create a client instance of MongoDB in Python

Now that we’ve reviewed the system requirements and set up a throwaway database, we can begin looking at our Python code. First, we’ll import the PyMongo library into the Python script and create a new client instance of the driver:

1
2
3
# import the pymongo MongoClient class
from pymongo import MongoClient
mongo_client = MongoClient('mongodb://localhost:27017')

Call the MongoClient’s database_names() method to return a list of all the database names in Python

Next, we’ll call the client’s database_names() method. This has the PyMongo client return a list of all MongoDB database names that exist on the server:

1
2
3
4
5
database_list = mongo_client.database_names()

# print the databases and the length of the list
print ("database_list:", database_list)
print ("number of db:", len(database_list))

Screenshot of Python IDLE get database_names() and collection_names() for MongoDB with PyMongo driver

We’ll use this list of databases in the next section to select one to be deleted or dropped.

Select the correct MongoDB database to drop

In this step, we’ll use the MongoClient class’s client instance to access a MongoDB database directly in our script by creating a database object. Then, we can use the database and collection objects to verify if there’s any data in them:

1
2
# WARNING: this database name will be selected for removal
db = mongo_client.unwanted_database

NOTE: It’s important to remember that Python doesn’t support hyphenated variable or object names. If you need to access a database name that contains a hyphen or dash, simply reference it like you would a dictionary key in Python:

1
2
# WARNING: this database name will be selected for removal
db = mongo_client["Unwanted-Database"]

This database object allows you to access a collection directly. You can use that collection object’s count_documents() method to determine the total number of documents in the collection. The method call is shown below:

1
2
col_obj = mongo_client["Unwanted-Database"]["Some Collection"]
docs = col_obj.count_documents({})

The docs object created will be an integer that represents the total number of documents in the MongoDB collection. You can iterate over the collections in a database using list_collection_names() (formerly called collection_names() in older versions of MongoDB):

1
2
3
db = mongo_client.unwanted_database
col_list = db.list_collection_names()
print ("collections on the unwanted db:", col_list)

Screenshot of Python IDLE accessing MongoDB database and its collections and document count

In the next section, we’ll be dropping the database we selected. Proceed only after you’ve verified that you’ve selected the correct database to drop.

WARNING: It’s worth repeating once again that you must make sure you’re dropping the correct database—- there is no undoing the API call to drop a MongoDB database, and the collections and documents in that database cannot be recovered from within MongoDB.

Use the drop_database() method to delete a MongoDB database with PyMongo

Once you have the database name, simply pass it as a string to the client instance’s drop_database() method to drop the MongoDB database:

1
mongo_client.drop_database('unwanted_database')

NOTE: This API call does not return a results object to verify that the call was successful. If you try assigning a variable to the method call, it will just return a NoneType object.

We can verify that the database was successfully dropped by making another call to the client instance’s database_names() method:

1
2
database_list = mongo_client.database_names()
print ("db names:", database_list)

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

If you prefer to work with the MongoDB Compass GUI, you can use this interface to verify that the database (as well as its collections and documents) was successfully dropped. It also offers another way to drop a database if you don’t want to use Python or the Mongo shell to do it.

Refresh the MongoDB databases in the Compass GUI application

If Compass has been running and was connected to the MongoDB server when you ran your script to drop the database, you’ll have to refresh the list of databases in the GUI. You can do this by clicking the small Refresh arrow on the left-hand side of the application. This will give you an accurate list of all the remaining databases in the MongoDB cluster:

Screenshot of MongoDB Compass GUI refreshing the databases

The database name that we deleted earlier in the Python script should no longer be visible in the GUI application at this point.

Drop a database using the Compass application

You can also use the GUI to drop a MongoDB database. Be sure to select the correct database, and then just click the trash can icon that will appear to the right of the database name.

Compass will then prompt the user to verify the name of the database selected to be dropped. You’ll need to type in the database name. Once the correct database name has been entered, the red DROP DATABASE button will be enabled—- simply click the button and the collection will be dropped:

Screenshot of the MongoDB Compass GUI dropping a database

Conclusion

When you need to drop a MongoDB database, it’s important to work carefully– dropping a database permanently removes the database and all of its collections. Using the PyMongo MongoClient class instance, it’s easy to accomplish this task in a Python script. All it takes is a few lines of code to drop a database with PyMongo, but you can also drop a database using the MongoDB Compass GUI application. No matter which method you choose, the instructions provided in this article will leave you well-prepared to drop a MongoDB database when needed.

In this article, we reviewed the Python code one section at a time. The complete Python script to drop a MongoDB database is shown below.:

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')

# get all of the database names
db_names_before_drop = mongo_client.database_names()
print ("db count BEFORE drop:", len(db_names_before_drop))

# access a database
db = mongo_client.unwanted_database

"
OR:
db = mongo_client["
unwanted_database"]
db = mongo_client["
Unwanted-Database"]
"


# check the collection names on the database
col_list = db.list_collection_names()
print ("collections on the unwanted db:", col_list)

# call MongoDB client object's drop_database() method to delete a db
mongo_client.drop_database('unwanted_database') # pass db name as string

# get all of the database names
db_names_after_drop = mongo_client.database_names()
print ("db count AFTER drop:", len(db_names_before_drop))

diff = len(db_names_before_drop) - len(db_names_after_drop)
print ("difference:", diff)

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.