How do I drop a MongoDB database using PyMongo?

Question:

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?

Asked By: qff

||

Answers:

PyMongo 2.4 up to at least 3.11.4

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

PyMongo 2.3 and earlier

from pymongo import Connection
connection = Connection('<HOST>', <PORT>)
connection.drop_database('<DBNAME>')
Answered By: qff
from pymongo import MongoClient
client = MongoClient('<HOST>', <PORT>)
client.db.command("dropDatabase")

see copydb example: https://api.mongodb.org/python/current/examples/copydb.html

You can also use runCommand helper to run other commands, detail see https://docs.mongodb.org/v3.0/reference/command/

Answered By: zydcom
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.