Ask for the shape you need.
Filter documents by values and operators, then return a deliberate ordered result.
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.
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"])Build 40 Review 30
03 Under the hood
- 1
The filter combines conditions on two fields. -1 requests descending order, while the secondary _id key breaks ties.
- 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
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
Find tasks tagged quality and return their names in ascending _id order.
Reveal one possible solution +
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
What does $gte mean?
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 ↗.