Arrays, Nested Fields and Results
Recipes hold lists and documents inside them. Query a field inside a field with dot notation, match values in arrays and whole items in arrays of documents, then choose which fields come back, sort them and show them a page at a time.
Updated
Arrays and Nested Fields
- Fields Inside Fields: Dot Notation (Apprentice): Dot notation names a field inside an embedded document, such as "nutrition.calories" in quotes, so a filter can test that one field instead of matching the whole embedded document.
- Querying Arrays: One Value, $all and $size (Apprentice): A filter on an array field matches when any item fits, $in matches when any item is one of a list, $all asks for every value in a list, and $size counts the items; an exact array match is rarely what you want.
- Arrays of Documents and $elemMatch (Journeyman): Dot notation reaches a field of every document in an array, such as "ingredients.name"; two such conditions can be met by two different items, and $elemMatch makes them hold for the same item.
Shaping Results
- Choosing Fields with Projections (Apprentice): A projection, the second argument to find, chooses which fields come back; 1 includes a field and 0 leaves it out, _id comes along unless you leave it out, and the two can't be mixed except for _id.
- Sorting and Paging: sort, limit and skip (Apprentice): sort puts results in order (1 up, -1 down) with a second field to break ties, limit caps how many come back, skip passes over the pages before, and countDocuments gives the number of pages.
Exercise: Ingredient Search
- Exercise: Ingredient Search (Apprentice): Write six mongosh queries for Sunday Kitchen's "what can I cook with what's in my fridge?" search, from recipes with chickpeas to page 2 of the best-rated, and let the tests run each one on the 40 recipes and check what it finds.