Python MongoDB Drop Collection
In MongoDB, you can drop (delete) an entire collection using the drop() method. Dropping a collection permanently removes all documents, indexes, and metadata associated with the collection.
Syntax of the drop() Method:
collection.drop()
Example: Dropping a Collection Using Python (PyMongo)
Step 1: Connect to MongoDB and Select a Database and Collection
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
# Select the collection to drop
mycol = mydb["customers"]
Step 2: Drop the Collection
# Drop the 'customers' collection
mycol.drop()
print("Collection dropped!")
Full Example of Dropping a Collection
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
# Select the collection
mycol = mydb["customers"]
# Drop the collection
mycol.drop()
print("Collection 'customers' has been dropped!")
Output:
Collection 'customers' has been dropped!
Once the collection is dropped, it is completely removed from the database, and you will need to recreate it if you want to use it again.
Important Notes:
- Dropping a collection cannot be undone.
- Use the
drop()method with caution, especially in production environments, as all data in the collection will be permanently lost.