Embedding and Referencing
In MongoDB, the shape of your documents decides speed and correctness more than anything else. Start from the questions the bike shop's app asks, then decide for each relationship whether to keep the data together in one document or link documents by their _id.
Updated
Designing for Your Queries
- Model for the Questions Your App Asks (Apprentice): Before deciding what goes in each document, list the app's screens and the question each one asks the database, then shape the documents so each common question is one short query.
Embed or Reference
- Embedding: Keeping Related Data Together (Apprentice): Embedding puts related data inside the document that uses it, like an order's line items and shipping address, so one read gets everything and one write saves it all at once, within a 16 MB limit per document.
- Referencing: Linking Documents by _id (Apprentice): Referencing links two documents by storing one's _id in the other, like a customerId in each order, so shared or changing data lives in one place, at the cost of a second query to follow the link.
- Choosing by Relationship: One-to-Few, One-to-Many, Many-to-Many (Journeyman): How many documents sit on each side of a relationship points to its model; embed a few, reference from the many side, never keep an array that grows without end, and link many-to-many with an array of ids.
Exercise: Model the Bike Shop's Orders
- Exercise: Model the Bike Shop's Orders (Journeyman): Add a customer, a product and an order to Riverbend Bike Shop's store in the right shape, embedding and referencing where each belongs, then answer three of the app's questions and explain each choice in a sentence.