A collection with a deliberate lifetime.
Create, inspect, and retire a uniquely named practice collection.
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.
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())True 1 False
03 Under the hood
- 1
The scratch name derives from the helper’s unique fixture name, keeping this example’s lifecycle away from unrelated collections.
- 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
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
Create an empty owned scratch collection, inspect its count, and drop it in finally.
Reveal one possible solution +
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
Does a Python collection handle alone guarantee stored documents exist?
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 ↗.