Build a pipeline, not a tangle.
Filter, group, project, and sort a report on the server.
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.
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"])Atlas 1 30 Orbit 2 60
03 Under the hood
- 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
A field path such as "$minutes" refers to each input document’s field. The literal 1 counts one per document in the group.
- 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
Calculate the total duration of all unfinished tasks as one aggregate.
Reveal one possible solution +
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
Why does stage order matter?
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 ↗.