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

A collection with a deliberate lifetime.

Create, inspect, and retire a uniquely named practice collection.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

A MongoDB database or collection handle can exist in Python before any corresponding data is stored. Writing generally materialises a namespace; create_collection makes creation explicit and can carry validation or other options. Dropping a collection removes its documents and indexes. Keep destructive lifecycle actions tied to an owned namespace rather than accepting arbitrary collection names from external input.

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_collection_lifecycle.py
from lab_support import mongo_lab

with mongo_lab() as collection:
    database = collection.database
    name = collection.name + "_scratch"
    scratch = database.create_collection(name)
    try:
        scratch.insert_one({"_id": 1, "name": "Practice"})
        print(name in database.list_collection_names())
        print(scratch.count_documents({}))
    finally:
        database.drop_collection(name)
    print(name in database.list_collection_names())
↳ EXPECTED OUTPUT
True
1
False

03 Under the hood

  1. 1

    The scratch name derives from the helper’s unique fixture name, keeping this example’s lifecycle away from unrelated collections.

  2. 2

    Explicit creation can fail if the namespace already exists. Choose whether that is a configuration error, an idempotent setup case, or evidence of an unexpected target.

  3. 3

    A production collection may have validation rules, indexes, change-stream consumers, and retention policies. Dropping it affects more than the current application’s visible records, so use reviewed administrative workflows.

04 Your turn, builder

A SMALL MISSION

Create an empty owned scratch collection, inspect its count, and drop it in finally.

Reveal one possible solution +
one_possible_solution.py
from lab_support import mongo_lab

with mongo_lab() as collection:
    database = collection.database
    name = collection.name + "_empty"
    scratch = database.create_collection(name)
    try:
        print(scratch.count_documents({}))
    finally:
        database.drop_collection(name)

05 Check your signal

QUICK SIGNAL CHECK

Does a Python collection handle alone guarantee stored documents exist?

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.