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 Hobbit