Embedded Objects and Arrays
A book has one publisher and several genres. In a relational schema those become three extra tables. In MongoDB they sit inside the book, and one read returns the whole picture. The skill is knowing how to reach inside, and knowing when not to embed.
The rule
Embed what belongs to the parent and stays small; reference what is shared or endless.
Two books from the collection in full:
{ _id: 1, title: "Dune", year: 1965, price: 9.99, stock: 12,
genres: ["sci-fi", "classic"],
publisher: { name: "Chilton", country: "US" },
ratings: [ { user: "asha", score: 5 }, { user: "ben", score: 4 } ] }
{ _id: 3, title: "Emma", year: 1815, price: 4.25, stock: 7,
genres: ["classic", "romance"],
publisher: { name: "John Murray", country: "UK" },
ratings: [] }- Embedded object:
publisheris a document inside a document. Reach inside with dot notation, in quotes:"publisher.country". - Array:
genresholds several values. A query on an array field matches if any element matches. - Array of objects:
ratingscombines both, so"ratings.score"reaches the score of every rating.
db.books.find({ "publisher.country": "UK" }) // Emma and The Hobbit
db.books.find({ genres: "classic" }) // Dune, Emma, The HobbitThe shortcut
For each related piece of data, ask two questions: Does it belong only to this parent? Will it stay small? Two yeses mean embed.
Genres
Only describe this book, a handful at most. Belongs and small: embed as an array.
The trap is forgetting the quotes: { publisher.country: "UK" } is a JavaScript syntax error. Dotted paths are always quoted strings.
Drills
Answer fast — trust the rule.
How do you match books whose publisher is in the US?
How many books match { genres: "classic" }?
Which data should NOT be embedded in a book document?
What is the maximum size of a single MongoDB document?
Remember
- Embed what belongs to the parent and stays small; reference what is shared or endless.
- Shortcut: two yeses (belongs, stays small) mean embed; reach in with quoted dot notation.
- Trap: an array query matches any element, and a document caps at 16 MB.
