Bobcares

Drop Collection MongoDB pymongo | Guide

by | Nov 12, 2023

Learn how to drop Collection MongoDB pymongo. Our MongoDB Support team is here to help you with your questions and concerns.

Drop Collection MongoDB pymongo | Guide

In MongoDB, a “collection” can be described as a container for storing and organizing related documents.

MongoDB is a NoSQL database that stores data in flexible, JSON-like BSON format.

Hence, we have to use the pymongo library to manage data in a MongoDB database if we are working with Python.

Furthermore, the drop_collection method is a part of pymongo. It helps delete or remove a collection from a MongoDB database.

How to drop a MongoDB Collection in Python

  1. To begin with, create a MongoDB Client for the MongoDB instance.
  2. Then, choose the database using the client object. Remember to make sure that the collection we are going to delete is present in this database.
  3. Next, choose the collection using the database object.
  4. After that, use the drop() function on the collection object. This will delete the collection from the database.

For example:

Here we want to delete a MongoDB collection named “Bobcats”.


import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# Use database named "organisation"
mydb = myclient["organisation"]
print("List of collections before deletion\n--------------------------")
for x in mydb.list_collection_names():
print(x)
# Get collection named "Bobcats"
mycol = mydb["Bobcats"]
# Delete or drop collection
mycol.drop()
print("\nList of collections after deletion\n--------------------------")
for x in mydb.list_collection_names():
print(x)
Copy

As you can see in the image below, the Bobcats collection is deleted. This is verified by the list of collections displayed after the deletion takes place.

Drop Collection MongoDB pymongo

[Need assistance with a different issue? Our team is available 24/7.]

Conclusion

In brief, our Support Experts demonstrated how to drop Collection MongoDB pymongo.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.