Drop Collection if already exists in MongoDB using Python


MongoDB is a widely popular open-source database that stores data in a flexible JSON like format. It does not use the orthodox technique of storing data in rows and columns. Instead, it uses a more flexible approach which increases its scalability.

This database is designed to handle large volumes of data and therefore, it is tailor made for modern applications. A MongoDB database consists of “collections” which is similar to a table in a RDBMS.

A collection is a group of documents consisting of fields with different types of values. A database can contain numerous collections and each collection can contain multiple documents. In this article, we will drop a MongoDB collection with the help of pythonic commands. Each collection has its own schema which depends upon the structure of the document.

Installing PyMongo

PyMongo is the python driver through which a programmer interacts with the “MongoDB” databases. It provides an interface to perform several operations on a MongoDB data from python. We can install “PyMongo” by using the python package manager on the command line −

pip install pymongo 

Once the PyMongo library is installed, we an import it on our local IDE.

Creating a Database

We need a reference database on which we will operate. Creating a MongoDB database is not a difficult task. We have to download the latest version of MongoDB from the internet and install it on the system. After this we will start the “MongoDB” server. We can use a default server with a default port number and begin with the “connection” process. We can manually create a database by passing the database name and collection name. The data can be imported in the form of a JSON or CSV file format.

Connecting MongoDB to Python through PyMongo

This is the most crucial step as it involves the creation of a connection between the two platforms. We will create a MongoClient object with the help of “pymongo.MongoClient()” function. The connection is established by passing the server address as an argument for this function.

Syntax

Mongo_client = pymongo.MongoClient("Connection address") 

Let’s apply this method to establish a connection.

Creating a Connection to Read a Collection in Python

Here we are trying to read a collection that is stored in MongoDB. In the example given below −

  • We imported the “PyMongo” library and created a “MongoClient” object which allows us to establish a connection and access the database

  • We passed a server address specifying the address name as “localhost”, which means that the MongoDB server is running on the same machine as the python program. We used the default port number for MongoDB server: “27017”.

  • After this we specified the database and collection name.

  • We have created a collection and populated it.

  • We used the “find()” method to retrieve the documents stored in the collection.

Example

import pymongo
Mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")

# Database name
database = Mongo_client["mydb"]

#Getting the database instance
database = Mongo_client['mydb']

#Creating a collection
collection = database['example']

#Inserting document into the collection
data = [{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}]
res = collection.insert_many(data)
print("Data inserted ......")

#Retreving the data
documents = collection.find()
print("Contents of the collection: ")
for document in documents:
   print(document)

Output

Data inserted ......
Contents of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}

Now, that we have created a database and a collection, let’s look at the methods to drop a collection from the database.

Dropping the Collection using the Drop() Method

This is a very simple approach of dropping a collection from the database. Let’s understand it.

  • After establishing the connection, we used the drop() method to drop the targeted collection from the database.

  • Once the collection is dropped we can’t retrieve it’s documents with the help of “find()” method.

  • None” is returned as the output since the collection has been dropped.

Example

import pymongo
Mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")

# Database name
database = Mongo_client["mydb"]

#Getting the database instance
database = Mongo_client['mydb']

#Creating a collection
collection = database['example']

documents = collection.find()
print("Contents of the collection: ")
for document in documents:
   print(document)

#dropping the collection
print(collection.drop())
print("Collection Dropped ......")

Output

F:\Examples>python test.py
Contents of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
None
Collection Dropped ......

If you try open the MongoDB database and verify for the collection , you can observe that the coll

Conclusion

This article focuses on a simple “MongoDB” operation of dropping a “collection” that exists in a database with the help of python programming. We used “PyMongo” library to access the MongoDB database. We established a connection and specified the targeted database and collection name. Finally, we used the “drop()” method to drop the collection from the database.

Updated on: 05-May-2023

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements