How do I drop a MongoDB database using PyMongo?

qff picture qff · Feb 17, 2016 · Viewed 20.6k times · Source

I want to drop a database in MongoDB similarly to

use <DBNAME>
db.dropDatabase()

in the Mongo shell.

How do I do that in PyMongo?

Answer

qff picture qff · Feb 17, 2016

PyMongo 2.4 up to at least 3.2.1

from pymongo import MongoClient
client = MongoClient('<HOST>', <PORT>)
client.drop_database('<DBNAME>')

From the PyMongo 3.2.1 documentation

PyMongo 2.3 and earlier

from pymongo import Connection
connection = Connection('<HOST>', <PORT>)
connection.drop_database('<DBNAME>')

From the PyMongo 2.3 documentation (and the PyMongo 1.0 documentation for completeness)