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

Meet the document store.

Connect to a dedicated practice replica set and understand client, database, and collection.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

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.

mongodb_connect.py
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"])
↳ EXPECTED OUTPUT
4
Build 40

03 Under the hood

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

    find_one returns one matching document or None. A projection asks for only the fields this caller needs.

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

A SMALL MISSION

Fetch the Atlas review task and print its name.

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

QUICK SIGNAL CHECK

What does find_one return when nothing matches?

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.