Delete collection in MongoDB using Python if it exists

WBOY
Release: 2023-08-21 20:34:46
forward
1146 people have browsed it

Delete collection in MongoDB using Python if it exists

MongoDB is a widely popular open source database that stores data in a flexible JSON-like format. It does not use traditional row and column data storage technology. Instead, it takes a more flexible approach that increases its scalability.

This database is designed to handle large amounts of data, and therefore, it is specifically customized for modern applications. The MongoDB database is composed of "set", which is similar to tables in a relational database.

A collection is a group of documents consisting of fields with different types of values. A database can contain multiple collections, and each collection can contain multiple documents. In this article, we will delete a MongoDB collection using Python commands. Each collection has its own schema, depending on the structure of the document.

Install PyMongo

PyMongo is the Python driver through which programmers interact with the "MongoDB" database. It provides an interface to perform multiple operations on MongoDB data from Python. We can install "PyMongo" by using the Python package manager on the command line.

pip install pymongo 
Copy after login

Once the PyMongo library is installed, we can import it in our local IDE.

Create database

We need a reference database to operate. Creating a MongoDB database is not a difficult task. We need to download the latest version of MongoDB from the internet and install it on the system. After that we will start the "MongoDB" server. We can use the default server and default port number and start the "Connect" process. We can manually create a database by passing the database name and collection name. Data can be imported in JSON or CSV file format.

Connecting MongoDB to Python via PyMongo

This is the most critical step as it involves establishing a connection between the two platforms. We will use the "pymongo.MongoClient()" function to create a MongoClient object. By passing the server address as a parameter to this function, a connection is established.

grammar

Mongo_client = pymongo.MongoClient("Connection address") 
Copy after login

Let’s apply this method to establish a connection.

Create a connection in Python to read a collection

Here we are trying to read a collection 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 the MongoDB server is running on the same machine as the Python program. We used the default port number of the MongoDB server: "27017".

  • After this, we specify the name of the database and collection.

  • We have created a collection and populated it.

  • We used the "find()" method to retrieve 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)
Copy after login

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'}
Copy after login

Now that we have created a database and a collection, let's look at how to delete a collection from the database.

Use the Drop() method to delete a collection

This is a very simple method for deleting a collection from the database. Let’s find out.

  • After the connection is established, we delete the target collection from the database using the drop() method.

  • Once a collection is deleted, we cannot use the "find()" method to retrieve its documents.

  • Because the collection has been deleted, the output is "None".

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 ......")
Copy after login

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 ......
Copy after login

You can observe this coll if you try to open a MongoDB database and validate the collection

in conclusion

This article focuses on the simple operation of using Python programming to delete the "MongoDB" collection that exists in the database. We use the "PyMongo" library to access the MongoDB database. We established the connection and specified the target database and collection name. Finally, we used the "drop()" method to delete the collection from the database.

The above is the detailed content of Delete collection in MongoDB using Python if it exists. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template