Start learning free

LESSON 51 OF 66 · NOSQL: MONGODB

Find with Filters

Practice

find_one stops at the first match. find(filter) finds every match, like SELECT … WHERE in SQL. This lesson runs on an in-memory MongoDB that already holds the shop; the same code runs unchanged on a real MongoDB server.

Operators: a plain value in a filter means equals. To compare, put a dict with an operator in its place: {"$lt": 5} means less than 5, $gt means greater than, and {"$in": [...]} matches any value in the list, like SQL's IN. Several fields in one filter must all match, like AND, and one field can take two operators to make a range.

Projection, sort and limit: a second dict, the projection, picks the fields to send back, like the column list after SELECT: 1 keeps a field, and _id comes back unless you set it to 0. find gives back a cursor that hands out the documents one at a time. .sort(field) orders it (add -1 for the biggest first, like DESC), .limit(n) keeps the first n, like LIMIT, and list() collects it. For example, on the customers:

fields = {"name": 1, "city": 1, "_id": 0}
found = db.customers.find({"city": {"$in": ["Paris", "Berlin"]}}, fields)
print(list(found.sort("name", -1).limit(3)))

Your script must print these 3 lines:

[{'name': 'Pen', 'price': 2}, {'name': 'Notebook', 'price': 7}]
[{'name': 'Mug', 'price': 12}, {'name': 'Plant', 'price': 15}, {'name': 'Teapot', 'price': 22}, {'name': 'Lamp', 'price': 29}]
[{'name': 'Teapot', 'price': 22}, {'name': 'Plant', 'price': 15}]

Your task: make one projection that keeps only name and price. With it, print three finds as lists: the office products priced under 8, sorted by price; the kitchen and home products, sorted by price; and the 2 priciest products priced over 10 and under 25.


Assignment
Follow the Coding Tutorial to write three filtered finds with one projection, then sort, limit and print them.


Hint
An operator dict goes where the value would be: {"price": {"$gt": 1}}. Chain the cursor calls in order: sort first, then limit, and wrap it all in list() to print it.


STEP 1 OF 7
    Ctrl + Enter to check