Remove only what you intend.
Use narrow predicates and inspect deletion results before declaring success.
01 The idea
delete_one removes at most one matching document; delete_many removes all matches. An empty filter matches every document, so it should never be the accidental result of a missing application condition. A delete result describes how many documents were deleted, not whether your business operation was conceptually correct.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from lab_support import mongo_lab
with mongo_lab() as collection:
result = collection.delete_one({"_id": 1, "done": True})
print("deleted:", result.deleted_count)
print("remaining:", collection.count_documents({}))deleted: 1 remaining: 3
03 Under the hood
- 1
The predicate includes a stable identity and the expected completed state. It cannot accidentally select an unfinished task with a different id.
- 2
deleted_count distinguishes a matching deletion from a no-op. Decide whether no match means already deleted, changed concurrently, or an invalid request.
- 3
The teaching helper drops its entire uniquely named fixture collection only during cleanup. That deliberate lifecycle operation is different from exposing an unbounded delete in an application.
04 Your turn, builder
Delete only unfinished tasks from Atlas and inspect the count.
Reveal one possible solution +
from lab_support import mongo_lab
with mongo_lab() as collection:
result = collection.delete_many({"project": "Atlas", "done": False})
print(result.deleted_count)05 Check your signal
What does an empty delete_many filter match?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.