Python MongoDB: Delete Document

Introduction

Deleting documents from a MongoDB collection is a crucial operation when managing your database. MongoDB provides powerful methods to delete single or multiple documents based on specified criteria. Python, with its extensive library support, makes it easy to interact with MongoDB. In this guide, we will use the pymongo library to delete documents from a MongoDB collection.

Setting Up

Install PyMongo

First, you need to install the PyMongo library. You can install it using pip:

pip install pymongo

Connecting to MongoDB

To delete documents from a MongoDB collection, you need to connect to the MongoDB server. The default hostname is localhost, and the default port is 27017.

Example: Connecting to MongoDB

from pymongo import MongoClient

# Connect to the MongoDB server
client = MongoClient('localhost', 27017)

# Verify connection
print("Connected to MongoDB server")

Creating a Database and Collection

Before deleting documents, you need to specify the database and collection where the documents are stored.

Example: Creating a Database and Collection

# Access a database
db = client['mydatabase']

# Access a collection
collection = db['employees']

print("Database and collection ready")

Inserting Documents

To demonstrate deleting documents, let’s insert some sample documents into the collection.

Example: Inserting Multiple Documents

# Insert multiple documents
employees = [
    {"name": "John Doe", "age": 28, "position": "Software Engineer"},
    {"name": "Jane Smith", "age": 32, "position": "Project Manager"},
    {"name": "Mike Johnson", "age": 45, "position": "CTO"},
    {"name": "Emma Davis", "age": 29, "position": "Data Scientist"},
    {"name": "Chris Evans", "age": 34, "position": "DevOps Engineer"}
]
collection.insert_many(employees)

print("Sample documents inserted")

Deleting Documents

You can delete documents from a collection using the delete_one() and delete_many() methods.

Example: Deleting a Single Document

The delete_one() method deletes the first document that matches the filter criteria.

# Delete a single document
result = collection.delete_one({"name": "John Doe"})
print("Documents deleted:", result.deleted_count)

Example: Deleting Multiple Documents

The delete_many() method deletes all documents that match the filter criteria.

# Delete multiple documents
result = collection.delete_many({"age": {"$gt": 30}})
print("Documents deleted:", result.deleted_count)

Verifying the Deletion

After deleting documents, you can verify the deletion by querying the collection.

Example: Querying the Collection

# Query the collection
documents = collection.find()
for doc in documents:
    print(doc)

Handling Exceptions

It’s important to handle exceptions that might occur during database operations to ensure that your program can handle errors gracefully.

Example: Handling Exceptions

from pymongo.errors import PyMongoError

try:
    # Delete a single document
    result = collection.delete_one({"name": "John Doe"})
    print("Documents deleted:", result.deleted_count)
except PyMongoError as e:
    print("An error occurred:", e)

Complete Example

Here is a complete example that includes connecting to MongoDB, creating a collection, inserting documents, deleting documents, and verifying the deletion.

from pymongo import MongoClient
from pymongo.errors import PyMongoError

# Connect to the MongoDB server
client = MongoClient('localhost', 27017)

# Access a database
db = client['mydatabase']

# Access a collection
collection = db['employees']

# Insert sample documents
employees = [
    {"name": "John Doe", "age": 28, "position": "Software Engineer"},
    {"name": "Jane Smith", "age": 32, "position": "Project Manager"},
    {"name": "Mike Johnson", "age": 45, "position": "CTO"},
    {"name": "Emma Davis", "age": 29, "position": "Data Scientist"},
    {"name": "Chris Evans", "age": 34, "position": "DevOps Engineer"}
]
collection.insert_many(employees)

# Delete a single document
try:
    result = collection.delete_one({"name": "John Doe"})
    print("Documents deleted:", result.deleted_count)
except PyMongoError as e:
    print("An error occurred:", e)

# Delete multiple documents
try:
    result = collection.delete_many({"age": {"$gt": 30}})
    print("Documents deleted:", result.deleted_count)
except PyMongoError as e:
    print("An error occurred:", e)

# Verify the deletion
print("Remaining documents in collection:")
try:
    documents = collection.find()
    for doc in documents:
        print(doc)
except PyMongoError as e:
    print("An error occurred:", e)

Conclusion

Deleting documents from a MongoDB collection using Python is straightforward with the pymongo library. By following the steps outlined above, you can easily connect to a MongoDB server, create collections, insert documents, and perform delete operations to manage your data. This provides a solid foundation for maintaining and manipulating your data programmatically using Python.

Leave a Comment

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

Scroll to Top