Python Tutorial
Python MongoDB - Delete
Remove one or many documents — with a filter, and never by accident.
delete_one
delete_one removes the first document matching the filter and reports how many were deleted.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
customers = client["mydatabase"]["customers"]
result = customers.delete_one({"address": "Mountain 21"})
print(result.deleted_count, "document(s) deleted") # 0 or 1delete_many
delete_many removes every document matching the filter.
result = customers.delete_many({"address": {"$regex": "^S"}})
print(result.deleted_count, "documents deleted") # all addresses starting with SThe Empty-Filter Trap
An empty filter {} matches every document. delete_many({}) empties the whole collection.
# customers.delete_many({}) <-- deletes EVERYTHING. Rarely intended.Always run the same filter through count_documents first to see exactly how many documents you are about to remove.
Preview Before Deleting
filter_ = {"last_login": {"$lt": "2023-01-01"}}
print("Will delete:", customers.count_documents(filter_))
result = customers.delete_many(filter_)
print("Deleted:", result.deleted_count)Find and Delete Atomically
find_one_and_delete removes a document and returns it — handy for queue-style "claim and remove" patterns.
job = client["tasks"]["queue"].find_one_and_delete(
{"status": "pending"})
if job:
print("Processing", job["_id"])Best Practices
- Always pass a filter unless you truly intend to clear the collection.
- Count matching documents before a
delete_many. - Consider a soft-delete flag (
{"deleted": True}) for recoverable data. - Use
find_one_and_deletefor atomic claim-and-remove workflows.
Try It Yourself
Exercise 1: Delete all documents where status is "expired" and print how many were removed.
Show solution
res = coll.delete_many({"status": "expired"})
print(res.deleted_count)Exercise 2: What does delete_many({}) do?
Show solution
It deletes every document in the collection — the empty filter matches everything.
📘 Real-World Deep Dive
Knowing <strong>MongoDB Delete (MongoDB)</strong> well is what turns MongoDB from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MongoDB Delete that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
db = MongoClient().shop
res = db.orders.delete_many({"status": "draft", "createdAt": {"$lt": "2020-01-01"}})
print("deleted:", res.deleted_count)Expected Output
(see source)Common mistakes
- Inserting a
dictwith embeddeddatetimeworks, but naivedatetime(without UTC) leads to subtle comparison bugs. - Queries with type-mismatched values silently return no results — cast at the boundary or use
bsoncodecs. find()returns a cursor — calllist(cursor)only once you intend to materialise results.- Treating MongoDB Delete as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Project only the fields you need:
collection.find({}, {"name": 1}). - Use
bulk_writeinstead of looping over single inserts / updates — order-of-magnitude faster. - Create indexes:
collection.create_index([("field", pymongo.ASCENDING)]). - When working with MongoDB, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.