Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python meets MongoDB
EXPERIMENT 93 / 101

Remove only what you intend.

Use narrow predicates and inspect deletion results before declaring success.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

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.

mongodb_delete.py
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({}))
↳ EXPECTED OUTPUT
deleted: 1
remaining: 3

03 Under the hood

  1. 1

    The predicate includes a stable identity and the expected completed state. It cannot accidentally select an unfinished task with a different id.

  2. 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. 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

A SMALL MISSION

Delete only unfinished tasks from Atlas and inspect the count.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What does an empty delete_many filter match?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.