← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 1 of 7

Embedding vs referencing

Embed data that is read together and reference data that is shared, large or changes independently.

In this page:

  1. Embedding vs referencing

Embedding vs referencing

Embedding stores related data inside one document for fast single-read access. Referencing stores ids and looks them up with a second query or $lookup.

Embed for one-to-few, owned, read-together data; reference for large, shared or frequently changing data.

Note: Design around how your application reads data, not around table diagrams.

Example: Embedding vs referencing

bash
test> db.users.insertOne({ _id: 1, name: "Ada", address: { city: "London", zip: "N1" } })
{ acknowledged: true, insertedId: 1 }
test> db.authors.insertOne({ _id: 7, name: "Ada" })
{ acknowledged: true, insertedId: 7 }
test> db.books.insertOne({ _id: 100, title: "Notes", authorId: 7 })
{ acknowledged: true, insertedId: 100 }
test> db.books.aggregate([{ $lookup: { from: "authors", localField: "authorId", foreignField: "_id", as: "author" } }, { $project: { _id: 0, title: 1, author: { $first: "$author.name" } } }])
[ { title: 'Notes', author: 'Ada' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Embedding unbounded lists
  2. Referencing everything like a relational database
  3. Duplicating data that changes often
Chapter Summary
  • Embed data read together
  • Reference shared or large data
  • Watch the 16 MB document limit
  • Design for query patterns

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.