Meet the document store.
Connect to a dedicated practice replica set and understand client, database, and collection.
01 The idea
MongoDB stores BSON documents in collections. PyMongo is the official Python driver. A MongoClient manages connections; a database groups collections; a collection stores documents. Creating these handle objects does not necessarily perform network I/O immediately, so the workbench pings the server before seeding data. The helper creates a uniquely named disposable collection for each example and drops only that collection on exit.
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:
print(collection.count_documents({}))
document = collection.find_one({"_id": 2}, {"_id": 0, "name": 1, "minutes": 1})
print(document["name"], document["minutes"])4 Build 40
03 Under the hood
- 1
Use the downloaded workbench to install PyMongo and start the local MongoDB replica set. The setup page explains the local-only connection URI and replica initialization step.
- 2
find_one returns one matching document or None. A projection asks for only the fields this caller needs.
- 3
MongoClient is intended to be reused within an application process. This teaching helper owns and closes its client so examples are isolated; a real service usually has a longer-lived client and explicit application shutdown.
04 Your turn, builder
Fetch the Atlas review task and print its name.
Reveal one possible solution +
from lab_support import mongo_lab
with mongo_lab() as collection:
document = collection.find_one({"project": "Atlas"})
if document is None:
raise LookupError("Practice task missing")
print(document["name"])05 Check your signal
What does find_one return when nothing matches?
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 ↗.