Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
MongoDB Basics  ›  Lesson

Embedded Objects and Arrays

Embedded Objects & Arrays 12 minA document can nest objects and arrays, reached with dot notation, and you embed data that belongs to one parent and stays bounded while referencing data that is shared or grows without limit.

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: publisher is a document inside a document. Reach inside with dot notation, in quotes: "publisher.country".
  • Array: genres holds several values. A query on an array field matches if any element matches.
  • Array of objects: ratings combines 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

The 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.

Deciding for the bookshopStep 1 of 4
  1. 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.

quick drill

How do you match books whose publisher is in the US?

quick drill

How many books match { genres: "classic" }?

quick drill

Which data should NOT be embedded in a book document?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainEmbed or reference?

The bookshop wants to store, for each book, its publisher's name and country, its list of genres, and every customer order that ever included it. Explain which of these you would embed in the book document and which you would keep in a separate collection, and why.