Exercise: Ingredient Search

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.

Apprentice · MongoDB · Updated

By

Sunday Kitchen's cooks keep asking the same question: "what can I cook with what's in my fridge?" The website's new search answers it from the ingredients on every card: recipes with chickpeas, recipes with both garlic and lemon, recipes that use at least 2 cups of flour, and dinners under 500 calories. It also needs a short dessert list and page 2 of the best-rated recipes. Each one is a query, and you'll write all six in mongosh syntax. Tests run your queries on the same 40 recipes as this chapter's lessons and check exactly what each one finds.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-mongodb-ingredient-search, also linked from the Exercise box beside the lesson. Clone it into your mongodb-course folder. In VS Code, open the mongodb-course folder, open the terminal with Terminal > New Terminal, and type:

git clone https://github.com/ask-codey/exercise-mongodb-ingredient-search.git

Git makes a folder, exercise-mongodb-ingredient-search, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal, and install the packages the tests use:

npm install

The folder holds:

  • queries.js: the six functions you'll finish.
  • data/recipes.json: Sunday Kitchen's 40 recipes with their nutrition and ingredients, the same ones you loaded in Fields Inside Fields: Dot Notation.
  • data/load-into-mongosh.js: loads those recipes into mongosh, so you can try a query there first.
  • test/: the tests, and the helper that runs your queries for them. You don't need to change either.

What to do

Every function in queries.js gets db, which works like it does in mongosh, and returns db.recipes.find({}) for now, which finds all 40 recipes. The comment above each function says exactly what it should find, with how many recipes and examples:

/*
 * 1. Find the recipes that use chickpeas: an ingredient whose name is "chickpeas".
 *
 *    Finds 3 recipes: Chickpea Curry, Falafel Wraps and Hummus.
 */
export function withChickpeas(db) {
  return db.recipes.find({});
}

Replace db.recipes.find({}) in each function with one mongosh statement of your own, after the word return:

  1. withChickpeas: the 3 recipes with an ingredient named "chickpeas", as above.
  2. garlicAndLemon: the 4 recipes with an ingredient named "garlic" and another named "lemon": Lentil Soup, Caesar Salad, Falafel Wraps and Hummus.
  3. twoCupsOfFlour: the 3 recipes where one ingredient is named "flour" and has an amount of 2 or more (every flour amount is in cups): Lemon Bars (2), Margherita Pizza (3) and Chocolate Chip Cookies (2.25). Banana Bread uses 1.75 cups of flour, so it doesn't count, even though its 3 bananas have an amount of 2 or more.
  4. lightDinners: the 10 dinners (meal: "dinner") whose nutrition.calories is under 500, such as Ratatouille (180) and Weeknight Chili (480). Green Curry has exactly 500, so it doesn't count.
  5. dessertList: the 6 desserts (meal: "dessert"), each with only two fields, name and minutes, and no _id, such as { name: "Tiramisu", minutes: 30 }.
  6. bestRatedPage2: page 2 of the best-rated recipes, five to a page. Sort by rating from highest to lowest, with recipes that have the same rating in name order from A to Z, then skip page 1's five and keep the next five. It finds, in this order: Shoyu Ramen (4.7), Tiramisu (4.7), Mango Sticky Rice (4.6), Saturday Pancakes (4.6) and Spaghetti Carbonara (4.6).

You can try each query in mongosh first. In the exercise folder's terminal, start mongosh, type use ingredient_search to choose a practice database, then load("data/load-into-mongosh.js") to put the 40 recipes in it. When a query finds the right recipes there, copy it into its function after return.

Check your work

Run the tests from the exercise folder:

npm test

At first every test fails. That's expected: each query you finish turns its test green. When a test fails, its message says what it expected and what your query found, for example 3) twoCupsOfFlour should find the 3 recipes where the same ingredient is named flour and has an amount of 2 or more. Banana Bread uses 1.75 cups of flour; its 3 bananas don't make it count., followed by the recipes your query found.

The tests start their own throwaway MongoDB, so they never change your databases. If you installed MongoDB in Setup: MongoDB, mongosh and Compass, they use it. If you didn't, the first npm test downloads MongoDB for the tests, nearly 1 GB on Windows and about 180 MB on a Mac, unless an earlier exercise already did; it's kept for every exercise after this one.

Hints

  • A field inside a field goes in quotes. "nutrition.calories" and "ingredients.name" are dot notation, from Fields Inside Fields: Dot Notation.
  • Two ingredients, or one? "Garlic and lemon" is two different ingredients, which Querying Arrays: One Value, $all and $size has the operator for. "2 cups of flour" is two conditions on the same ingredient, which is what Arrays of Documents and $elemMatch is about.
  • Watch the edge. "Under 500" leaves out a dinner with exactly 500 calories, and the tests check one.
  • The second pair of braces chooses the fields. Choosing Fields with Projections shows how to leave out _id.
  • Sort, then page. Sorting and Paging: sort, limit and skip shows how to break a tie with a second field and which page skip gives.

When you're done

Every test is green, and npm test prints:

✔ 1) withChickpeas finds the 3 recipes that use chickpeas (1065.3509ms)
✔ 2) garlicAndLemon finds the 4 recipes that use both garlic and lemon (10.1167ms)
✔ 3) twoCupsOfFlour finds the 3 recipes with one ingredient that is 2 or more cups of flour (10.0964ms)
✔ 4) lightDinners finds the 10 dinners under 500 calories (9.6715ms)
✔ 5) dessertList finds the 6 desserts, each with only its name and minutes (9.5659ms)
✔ 6) bestRatedPage2 finds page 2 of the best-rated recipes, five to a page, in order (10.2556ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1429.0176

The times in parentheses will be different on your computer. Now look at twoCupsOfFlour again. If a cook added a recipe that used 4 tablespoons of flour, would your query find it by mistake? What would you add, and where, so it wouldn't?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here.

  1. On GitHub, click +, then New repository. Name it (for example exercise-mongodb-ingredient-search), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-mongodb-ingredient-search.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-mongodb-ingredient-search, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

A search box with filters is a handful of queries: a value in a list, two conditions on one item, a field inside a field, the fields a page shows, and the page itself. You can now write each one and check it against the data.

Key terms

Related