Up Next: Modeling

Look back at the queries and changes you can write after Module 2, see them work together behind a recipe search page, and get a first look at Module 3, where you decide the shape of the documents for a whole online store.

Apprentice · MongoDB · Updated

By

After this lesson you can

  • Choose the Module 2 query or change a Sunday Kitchen task needs, from filters, projections, sort and paging to updates and deletes

Key takeaways

  • After Module 2 you can add documents in batches, find exactly the ones you want, choose their fields, sort and page them, and change and delete them safely.
  • A recipe site's search page is built from the queries you know now: a filter for each choice the visitor makes, then a sort and a page.
  • Each job has a tool. A filter picks documents, a projection picks fields, sort, limit and skip page the results, and update operators change them.
  • Module 3 is about the shape of documents, such as whether an order holds its items inside it or points to them.

At the start of this module, you could add a recipe and list them all. Now you can ask the database real questions and change exactly what you mean to change. That's most of what an app's screens ask of a database every day: a search box, a filtered list, a page of results, a Save button and a Delete button.

This lesson looks back at what you can do, puts it together on one search page, and gives you a first look at Module 3, where the question changes from "how do I ask?" to "what shape should the documents be?"

What you can do now

After Module 2, you can:

  • add documents in batches with insertMany, or a whole file with load();
  • find exactly the documents you want with find, findOne and countDocuments, comparison operators such as $gte and $in, and $or, $not, null and $exists;
  • reach inside documents with dot notation, and into arrays with $all and $elemMatch;
  • shape the results with a projection, and sort and page them with sort, limit and skip;
  • change documents with $set, $unset, $inc, $push, $pull, $addToSet and upserts;
  • delete safely, checking the filter with find first, or archiving instead.

Here's a question from Sunday Kitchen's home page, "our three best-rated vegetarian dinners", answered in one query. Load the recipes first if you've changed them:

load("sunday-kitchen-recipes.js")
true
db.recipes.find({ meal: "dinner", vegetarian: true }, { _id: 0, name: 1, rating: 1 }).sort({ rating: -1, name: 1 }).limit(3)
[
  { name: 'Chickpea Curry', rating: 4.7 },
  { name: 'Margherita Pizza', rating: 4.3 },
  { name: 'Black Bean Tacos', rating: 4.2 }
]

A filter, a projection, a sort with a second field to break the tie at 4.2, and a limit. A module ago, each part of that line was new. Now you can read it from left to right.

Putting it together: a search page

A recipe site's search page puts the whole module to work. Each choice a visitor makes adds a piece to one query:

  • a cuisine, and a longest time in minutes;
  • an ingredient to include and one to leave out, for the fridge and for allergies;
  • a lowest rating;
  • the sort order and the page, so the results come a page at a time.

A visitor may pick one choice or all of them at once, and the query has to be right either way.

Which tool fits?

Building a page like that, like most work with a database, comes down to one question for each step: which tool does this job?

The job The tool
Pick the documents a filter in find, with operators such as $lte, $in and $or
Pick a field inside a field dot notation: "nutrition.calories"
Two conditions on the same array item $elemMatch
Show only some fields a projection: { name: 1, minutes: 1 }
Put the results in order and take a page sort, skip and limit
Change some fields updateOne or updateMany with $set
Count up, or add to a list $inc, $push or $addToSet
Create it, or change it if it's there an update with upsert: true
Remove documents deleteMany, after find with the same filter

A sneak peek: one order, one document

Module 3 leaves the kitchen for a bike shop. Riverbend Bike Shop sells online, and every order has a customer and a list of items. Here's one order, with its items inside it (try it in sunday_kitchen; Module 3 gives the shop a database of its own):

db.orders.insertOne({ _id: 1001, customerId: 7, items: [ { product: "Trail Helmet", quantity: 1 }, { product: "Bike Lights", quantity: 2 } ] })
{ acknowledged: true, insertedId: 1001 }
db.orders.findOne({ _id: 1001 })
{
  _id: 1001,
  customerId: 7,
  items: [
    { product: 'Trail Helmet', quantity: 1 },
    { product: 'Bike Lights', quantity: 2 }
  ]
}

The items live inside the order, so one findOne brings back the whole order. The customer is only a number, customerId: 7, that points to a document in another collection. Why put one inside and point to the other? That choice, made for every relationship in an app, is what Module 3 teaches.

What Module 3 unlocks

Module 3, Modeling, designs the documents for Riverbend Bike Shop's whole store:

  • Embedding and referencing: start from the questions the app asks, then decide what goes inside a document and what gets its own collection.
  • Patterns and validation: shapes that work again and again, and rules that make MongoDB turn away a product with a missing price.
  • Transactions and the relational choice: keeping a checkout from selling the last bike twice, and an honest look at when a relational database is the better home for the data.

By its end, you can model a whole store for documents and explain each choice. Those decisions are the ones that make an app fast and correct, or slow and full of surprises.

Check yourself

2 questions to try on the lesson page.

So what

You can now answer an app's everyday questions and make its everyday changes in mongosh. A search page like the one above is all of it at once, and Module 3 shows you how to shape the documents so those questions stay simple to answer.

Key terms

Related