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

Ask for the shape you need.

Filter documents by values and operators, then return a deliberate ordered result.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

01 The idea

PyMongo queries use filter documents rather than SQL strings. Operators such as $gte and $in express comparisons and membership. Projections choose fields; sort defines order; limit bounds the result. Treat an external filter as structured input that needs validation instead of passing arbitrary user-supplied operator documents straight to the database.

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

with mongo_lab() as collection:
    cursor = collection.find({"done": False, "minutes": {"$gte": 20}}, {"_id": 0, "name": 1, "minutes": 1}).sort([("minutes", -1), ("_id", 1)]).limit(2)
    for document in cursor:
        print(document["name"], document["minutes"])
↳ EXPECTED OUTPUT
Build 40
Review 30

03 Under the hood

  1. 1

    The filter combines conditions on two fields. -1 requests descending order, while the secondary _id key breaks ties.

  2. 2

    The projection excludes _id and includes name and minutes. Except for _id, inclusion and exclusion generally should not be mixed in one projection.

  3. 3

    find returns a cursor, which is consumed as results are retrieved. Convert to a list only when the result is intentionally bounded; a large collection should not be loaded casually into memory.

04 Your turn, builder

A SMALL MISSION

Find tasks tagged quality and return their names in ascending _id order.

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

with mongo_lab() as collection:
    for document in collection.find({"tags": "quality"}, {"name": 1}).sort("_id", 1):
        print(document["name"])

05 Check your signal

QUICK SIGNAL CHECK

What does $gte mean?

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.