Embedding vs referencing
Embed data that is read together and reference data that is shared, large or changes independently.
In this page:
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
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
- Embedding unbounded lists
- Referencing everything like a relational database
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: