Modeling and indexes

Choose embedding or references

Embed data read and changed together, and reference data with independent ownership, growth, or many-to-many relationships.

9 minute lesson

~~~

Every relationship in a MongoDB schema gets one of two treatments. Embedding puts the related data inside the parent document. Referencing stores it in its own collection and keeps only an ID in the parent.

Here are authors and posts modeled both ways. Embedded:

// posts collection — author details inside
{
  _id: ObjectId('...'),
  title: 'My first post',
  author: { name: 'Flavio', twitter: '@flaviocopes' },
  body: '...'
}

Referenced:

// posts collection — only a pointer
{ _id: ObjectId('...'), title: 'My first post', authorId: ObjectId('64ff...'), body: '...' }

// authors collection — the authoritative record
{ _id: ObjectId('64ff...'), name: 'Flavio', twitter: '@flaviocopes' }

Embedding wins on reads: the post page needs one query instead of two. It also wins on atomicity — a write to a single document is atomic, so the post and its embedded author details can never disagree mid-update.

Referencing wins when the related entity has a life of its own. Ask three questions:

Does it change independently? If the author renames themselves, the referenced version updates one document. The embedded version leaves stale copies in every post until you update them all.

Does it grow without bound? An author’s list of posts embedded inside the author document grows forever. Referenced posts do not.

Is it many-to-many? Tags shared across thousands of posts should not be copied into each one with no plan for updates.

Duplication is allowed — with a name attached

The two options combine. A common production pattern keeps the reference and embeds the one or two fields the read path needs:

{ title: 'My first post', authorId: ObjectId('64ff...'), authorName: 'Flavio' }

This is deliberate duplication. It is fine as long as you name the authoritative copy (the authors collection) and the update plan (a rename triggers an updateMany on posts). Duplication without that plan is how data quietly rots: the profile page shows the new name, old posts show the old one, and nobody can say which is correct.

Work through the exercise: model authors and posts both ways, then list which changes are cheap and which are painful in each version. Renames, deletes, and “show all posts by author” make the trade-offs concrete fast.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →