Skip to the workspace
Pebellslearn by building
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.

mongodb / Embedded Objects and Arrays

Explore each scene at your own pace.

01 · The rule

The rule

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
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.