Documents and Why They Fit

Why store a recipe as one document instead of rows in several tables? Meet the NoSQL families and where documents fit, honestly, including when a table is the better home. Then learn to write a document from scratch: fields and values, quotes and braces, arrays, documents inside documents, and the types MongoDB stores.

Updated

Tables or Documents

  1. Tables and Documents: Two Ways to Store a Recipe (Novice): A recipe card with lists of ingredients and steps breaks a single spreadsheet table; a relational database splits it into tables joined back together, and a document database keeps the whole card in one document.
  2. The NoSQL Families in Plain Words (Novice): NoSQL means "not only SQL", the databases that don't keep their data in relational tables; its four families store key-value pairs, documents, wide rows of columns or a graph of connections, and MongoDB is a document database.
  3. Where Documents Fit, and Where They Don't (Apprentice): Documents fit data that is read together, holds lists and changes shape over time; a relational database is often the better choice when many records must change together, when the same data is combined in many ways, or when a strict shape is the point.

The Shape of a Document

  1. Documents: Fields, Values, Quotes and Braces (Novice): A document is written like a filled-in form, with braces around it, a field name, a colon and a value for each line, commas between them, and quotes around text but not around numbers or true and false; mongosh's errors point at the punctuation that's missing.
  2. Arrays and Documents Inside Documents (Novice): Square brackets hold a list, called an array, such as a recipe's tags; braces inside a document hold a document inside a document, such as its nutrition box; and a list of documents holds the ingredients, each with a name, an amount and a unit.
  3. BSON Types and the _id Field (Apprentice): MongoDB stores documents as BSON, which adds types JSON doesn't have; whole numbers become int and decimals double, money goes in NumberDecimal and dates in ISODate, and every document has an _id, an ObjectId unless you choose your own.

Exercise: Recipe Cards as Documents

  1. Exercise: Recipe Cards as Documents (Apprentice): Turn three of Sunday Kitchen's handwritten recipe cards into documents with the right types, arrays and nested documents, insert each with insertOne, and let the tests read them back and check every field and its type.

Up Next: Queries

  1. Up Next: Queries (Novice): Look back at what you can do after Module 1, and get a first look at Module 2, where every screen of an app becomes a query that finds, sorts, pages and changes documents.