MongoDB Delete

Remove documents from your MongoDB collections safely

🗑️ Deleting Documents

MongoDB provides methods to delete documents from collections. You can delete one document, multiple documents, or all documents that match specific criteria. Always be careful when deleting data!


import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["store"]
products = db["products"]

# Delete one product
result = products.delete_one({"name": "Old Product"})
print(f"Deleted {result.deleted_count} document")
                                    
One
delete_one()
Many
delete_many()
Safe
Always Check

Delete Methods

1️⃣

Delete One

Remove first matching document

# Delete one document
products.delete_one({"name": "Old Item"})
🔢

Delete Many

Remove all matching documents

# Delete multiple documents
products.delete_many({"price": {"$lt": 10}})

Check Results

Verify deletion success

# Check how many deleted
result = products.delete_one({"_id": "123"})
print(f"Deleted: {result.deleted_count}")
🛡️

Safe Deletion

Find before deleting

# Check first, then delete
if products.find_one({"name": "Item"}):
    products.delete_one({"name": "Item"})

Delete One Document

Remove the first document that matches your criteria

🔹 Delete by Name

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["shop"]
products = db["products"]

# Delete one specific product by name
result = products.delete_one({"name": "Broken Widget"})

if result.deleted_count > 0:
    print("✅ Product deleted successfully")
else:
    print("❌ No product found to delete")

🔹 Delete by ID

# Delete one product by ID
product_id = "507f1f77bcf86cd799439011"
result = products.delete_one({"_id": product_id})

print(f"Documents deleted: {result.deleted_count}")

🔹 Safe Deletion with Check

# Safe deletion - check first
product_to_delete = products.find_one({"name": "Test Product"})
if product_to_delete:
    print(f"Found product: {product_to_delete['name']}")
    result = products.delete_one({"name": "Test Product"})
    print(f"Deleted: {result.deleted_count} document")
else:
    print("Product not found")

Delete Multiple Documents

Remove all documents that match your criteria

# Delete all products under $5
result = products.delete_many({"price": {"$lt": 5}})
print(f"Deleted {result.deleted_count} cheap products")

# Delete all out-of-stock items
result = products.delete_many({"stock": 0})
print(f"Deleted {result.deleted_count} out-of-stock items")

# Delete products from specific category
result = products.delete_many({"category": "discontinued"})
print(f"Deleted {result.deleted_count} discontinued products")

# Delete with multiple conditions
result = products.delete_many({
    "$and": [
        {"price": {"$lt": 10}},
        {"rating": {"$lt": 2}}
    ]
})
print(f"Deleted {result.deleted_count} cheap, low-rated products")

Safe Deletion Practices

Always verify what you're deleting before removing data

# Count documents before deleting
def safe_delete_many(collection, query):
    # First, see how many documents match
    count = collection.count_documents(query)
    
    if count == 0:
        print("No documents match the criteria")
        return
    
    print(f"Found {count} documents to delete")
    
    # Show a few examples
    examples = collection.find(query).limit(3)
    print("Examples of documents to be deleted:")
    for doc in examples:
        print(f"- {doc.get('name', 'Unknown')} (ID: {doc['_id']})")
    
    # Ask for confirmation (in real app, you'd get user input)
    confirm = True  # In real code: input("Delete these? (y/n): ").lower() == 'y'
    
    if confirm:
        result = collection.delete_many(query)
        print(f"✅ Deleted {result.deleted_count} documents")
    else:
        print("❌ Deletion cancelled")

# Example usage
safe_delete_many(products, {"price": {"$lt": 1}})

# Backup important data before deletion
def backup_before_delete(collection, query, backup_collection):
    # Find documents to delete
    docs_to_delete = list(collection.find(query))
    
    if docs_to_delete:
        # Backup to another collection
        backup_collection.insert_many(docs_to_delete)
        print(f"Backed up {len(docs_to_delete)} documents")
        
        # Now safe to delete
        result = collection.delete_many(query)
        print(f"Deleted {result.deleted_count} documents")
    else:
        print("No documents to delete")

# Create backup collection and use it
backup_products = db["products_backup"]
backup_before_delete(products, {"category": "old"}, backup_products)

Practical Delete Examples

Real-world deletion scenarios

# User account deletion
def delete_user_account(user_id):
    users = db["users"]
    
    # Check if user exists
    user = users.find_one({"_id": user_id})
    if not user:
        print("User not found")
        return False
    
    print(f"Deleting account for: {user['name']}")
    
    # Delete user's orders first
    orders = db["orders"]
    order_result = orders.delete_many({"user_id": user_id})
    print(f"Deleted {order_result.deleted_count} orders")
    
    # Delete user account
    user_result = users.delete_one({"_id": user_id})
    print(f"Deleted user account: {user_result.deleted_count}")
    
    return True

# Cleanup old data
def cleanup_old_logs():
    logs = db["logs"]
    
    # Delete logs older than 30 days
    from datetime import datetime, timedelta
    thirty_days_ago = datetime.now() - timedelta(days=30)
    
    result = logs.delete_many({
        "created_at": {"$lt": thirty_days_ago}
    })
    
    print(f"Cleaned up {result.deleted_count} old log entries")

# Remove duplicate products
def remove_duplicates():
    # Find products with same name
    pipeline = [
        {"$group": {
            "_id": "$name",
            "count": {"$sum": 1},
            "docs": {"$push": "$_id"}
        }},
        {"$match": {"count": {"$gt": 1}}}
    ]
    
    duplicates = list(products.aggregate(pipeline))
    
    for dup in duplicates:
        # Keep first, delete rest
        ids_to_delete = dup["docs"][1:]  # Skip first one
        result = products.delete_many({"_id": {"$in": ids_to_delete}})
        print(f"Removed {result.deleted_count} duplicates of '{dup['_id']}'")

# Run examples
delete_user_account("user123")
cleanup_old_logs()
remove_duplicates()

🧠 Test Your Knowledge

Which method deletes only one document?

What should you do before deleting important data?

How do you check how many documents were deleted?