Python MongoDB Tutorial – Delete Document with PyMongo

Last updated 5 months, 1 week ago | 385 views 75     5

Tags:- Python MongoDB

Deleting documents in a MongoDB collection is a fundamental operation, especially when managing data that is outdated, incorrect, or no longer needed. With PyMongo, Python developers can easily perform deletion operations using intuitive methods.

In this tutorial, you'll learn how to delete documents from MongoDB collections using Python’s PyMongo library.


Table of Contents

  1. Introduction

  2. Prerequisites

  3. Installing PyMongo

  4. Connecting to MongoDB

  5. Inserting Sample Data

  6. Deleting a Single Document (delete_one)

  7. Deleting Multiple Documents (delete_many)

  8. Deleting All Documents

  9. Deleting with Query Conditions

  10. Complete Working Example

  11. Tips and Common Pitfalls


1. Introduction

MongoDB provides two main methods for deleting documents:

  • delete_one() – deletes the first matching document.

  • delete_many() – deletes all matching documents.

Both return a result object that provides metadata, such as the number of documents deleted.


⚙️ 2. Prerequisites

  • Python 3.x installed

  • MongoDB server running locally or via MongoDB Atlas

  • Basic understanding of Python and MongoDB collections


3. Installing PyMongo

To install the PyMongo library, use pip:

pip install pymongo

4. Connecting to MongoDB

Local MongoDB connection:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

5. Inserting Sample Data

Let’s insert some test users into the users collection:

collection.insert_many([
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "Alice", "age": 28}
])

Now you have two documents with the name "Alice".


❌ 6. Deleting a Single Document

Use delete_one() to remove the first matching document:

result = collection.delete_one({"name": "Alice"})
print(f"Deleted {result.deleted_count} document.")

Only one of the "Alice" records will be deleted, even though there are two.


7. Deleting Multiple Documents

To delete all documents matching a condition, use delete_many():

result = collection.delete_many({"name": "Alice"})
print(f"Deleted {result.deleted_count} documents.")

Both "Alice" records will be deleted if you haven't already deleted one with delete_one().


8. Deleting All Documents

To delete all documents in a collection:

result = collection.delete_many({})
print(f"Deleted {result.deleted_count} documents.")

⚠️ Warning: This removes everything in the collection.


9. Deleting with Query Conditions

You can delete based on any condition or combination of conditions:

Example: Delete users older than 30

result = collection.delete_many({"age": {"$gt": 30}})
print(f"Deleted {result.deleted_count} documents.")

This will delete users like Charlie (age 35).


10. Complete Working Example

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

# Insert sample data
collection.insert_many([
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "Alice", "age": 28}
])

# Delete one Alice
res1 = collection.delete_one({"name": "Alice"})
print(f"Deleted {res1.deleted_count} document.")

# Delete all remaining users named Alice
res2 = collection.delete_many({"name": "Alice"})
print(f"Deleted {res2.deleted_count} documents.")

# Delete users older than 30
res3 = collection.delete_many({"age": {"$gt": 30}})
print(f"Deleted {res3.deleted_count} documents.")

# Optional: Clean up all
# res4 = collection.delete_many({})
# print(f"Deleted {res4.deleted_count} documents.")

11. Tips and Common Pitfalls

Tip / Pitfall Advice or Explanation
Deleting without conditions Always double-check your filters to avoid mass deletion
delete_one() deletes only one match If multiple documents match, only the first one is deleted
Check deleted_count Useful for logging and debugging
Use confirmation before deletion Especially for bulk or unconditional deletions
Back up critical data Before running any delete operation in production

✅ Conclusion

Deleting documents from MongoDB using Python is efficient and easy with PyMongo. Whether you need to remove one document or many based on conditions, PyMongo provides straightforward methods to handle it.

By mastering deletion operations, you ensure better data hygiene and application performance.