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

Build a pipeline, not a tangle.

Filter, group, project, and sort a report on the server.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

An aggregation pipeline sends documents through ordered stages. $match filters, $group calculates per-key results, $project reshapes, and $sort orders the output. Stage order affects both meaning and performance. Keep the data you need, filter deliberately, and inspect intermediate shapes when the result is surprising.

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

with mongo_lab() as collection:
    pipeline = [
        {"$match": {"done": False}},
        {"$group": {"_id": "$project", "minutes": {"$sum": "$minutes"}, "tasks": {"$sum": 1}}},
        {"$sort": {"_id": 1}},
    ]
    for document in collection.aggregate(pipeline):
        print(document["_id"], document["tasks"], document["minutes"])
↳ EXPECTED OUTPUT
Atlas 1 30
Orbit 2 60

03 Under the hood

  1. 1

    The first stage removes completed tasks before totals are calculated. Moving a condition after grouping would require a different field shape and could change the answer.

  2. 2

    A field path such as "$minutes" refers to each input document’s field. The literal 1 counts one per document in the group.

  3. 3

    Group output is not ordered automatically. Include a deterministic sort for reports. Larger pipelines can use $lookup for cross-collection relationships, but consider cardinality and whether embedding would better fit the access pattern.

04 Your turn, builder

A SMALL MISSION

Calculate the total duration of all unfinished tasks as one aggregate.

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

with mongo_lab() as collection:
    rows = list(collection.aggregate([{"$match": {"done": False}}, {"$group": {"_id": None, "minutes": {"$sum": "$minutes"}}}]))
    print(rows[0]["minutes"] if rows else 0)

05 Check your signal

QUICK SIGNAL CHECK

Why does stage order matter?

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.