Start learning free

LESSON 52 OF 66 · NOSQL: MONGODB

Reach Inside: Nested Fields and Lists in Python

Practice

A product document isn't flat: its stock field holds a dict (the Mug's is {'count': 10, 'warehouse': 'A'}) and its tags field holds a list. Filters can reach inside both. This lesson runs on an in-memory MongoDB that already holds the shop; the same code runs unchanged on a real MongoDB server.

Dot paths: the string "stock.count" is a dot path: it checks the count inside each document's stock dict, and operators like $lt work on it too. A whole dict as the value is different: the field must equal that dict exactly, with nothing more.

Lists and missing fields: on a list field, a plain value matches when the list holds it anywhere; a whole list as the value must equal the field's list exactly. The $exists operator asks whether a field is there at all: with False it finds the documents without it, like the Gift card, whose category SQL showed as NULL. For example:

print(names(db.products.find({"stock.warehouse": "B"})))
print(names(db.products.find({"stock.count": {"$gt": 20}})))
print(names(db.products.find({"tags": "ceramic"})))
print(names(db.customers.find({"email": {"$exists": True}})))

The starting code has a helper, names(cursor), that returns the sorted names of the documents a find gives back. Your script must print these 6 lines:

['Notebook']
[]
['Plant', 'Teapot']
['Gift card', 'Lamp', 'Mug', 'Plant']
['Gift card']
['Gift card']

Your task: print the names six filters find: a stock count of 0, with a dot path; a stock equal to the dict {"count": 0}; warehouse A with a stock count under 10; tags holding "gift"; tags equal to the list ["gift"]; and no category field at all.


Assignment
Follow the Coding Tutorial to print the names found by dot paths, list filters and $exists.


Hint
A dot path is one string in quotes, used as the key of the filter. The second and fifth lines are there to compare: a whole dict or a whole list as the value must match exactly, so they find little or nothing.


STEP 1 OF 6
    Ctrl + Enter to check

    Mongo Nested in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free