← Back to Node.js, page 9

nodejs-0173 · Medium mid

How do you model data in MongoDB: when do you embed documents, when do you reference them, and what are the document size limits?

Embed data that is read together with its parent, is bounded in size and has the same lifecycle (an address, order line items). Reference data that is large or unbounded, shared by many parents, or changed often on its own (comments on a popular post). A document cannot exceed 16 MiB, so never embed an array that grows without limit. Design the model around your queries, then add indexes that match them.

Full answer

MongoDB modeling starts from access patterns, not from entities.

Embed when

  • The child is almost always read with the parent (order and its line items).
  • The child set is small and bounded (a user with 3 addresses).
  • The child has no independent life and is updated together with the parent. One read, one atomic write for the whole document.

Reference when

  • The child set is large or unbounded (comments, log events). The 16 MiB document limit and the cost of rewriting a huge document make embedding unsafe.
  • Many parents share the child (a course shared by many students), or the child changes often by itself.
  • You need to query the child alone.
  • Referencing costs a second query or a $lookup, and consistency across documents needs care (transactions exist but are slower).

Patterns

  • Hybrid: embed a summary and reference the full data (the latest 3 comments inside the post, all comments in their own collection).
  • Bucketing: group time series data per hour or day to reduce the document count.
  • Denormalise on purpose: copy a name or title to avoid joins, and update copies when they change.
  • Computed fields: store counters (commentCount) instead of counting each time.

Indexes

  • Index fields used in filters and sorts. A compound index follows the ESR rule: equality fields first, then sort fields, then range fields.
  • Every index slows writes and uses memory. Review with explain().
  • Avoid unbounded arrays inside indexed fields (multikey index growth).

Mongoose note: populate() is a client-side join, which runs extra queries.

javascript
// A small simulation: how many reads does each model need, and how big does an embedded array get?
const posts = [{ id: 1, title: 'Intro to Node', author: 'Asha' }];
const comments = Array.from({ length: 1000 }, (_, i) => ({ postId: 1, user: 'user' + i, text: 'A typical comment with some words in it, number ' + i }));

let reads = 0;
const collections = {
  postsEmbedded: [{ ...posts[0], comments }],
  posts,
  comments,
};
const find = (name, predicate) => { reads++; return collections[name].filter(predicate); };

// Model A: comments embedded in the post. One read.
reads = 0;
const [embedded] = find('postsEmbedded', (p) => p.id === 1);
console.log('embedded model   : reads =', reads, '| comments loaded =', embedded.comments.length);

// Model B: comments in their own collection, with a limit as a real query would have.
reads = 0;
const [post] = find('posts', (p) => p.id === 1);
const firstTen = find('comments', (c) => c.postId === post.id).slice(0, 10);
console.log('referenced model : reads =', reads, '| comments loaded =', firstTen.length, '(paged)');

// The size of a growing embedded array, compared with the 16 MiB limit (JSON size is only an approximation of BSON size).
const LIMIT = 16 * 1024 * 1024;
const bytesPerComment = Buffer.byteLength(JSON.stringify(comments[0]));
console.log('one comment is about', bytesPerComment, 'bytes');
console.log('the 16 MiB limit is reached after about', Math.round(LIMIT / bytesPerComment / 1000) * 1000, 'comments');
console.log('rewriting a document with 1000 comments moves about', Math.round(Buffer.byteLength(JSON.stringify(embedded)) / 1024), 'KiB per update of the post');

// Hybrid: keep a bounded preview inside the post and the rest in the comments collection.
const hybrid = { ...posts[0], commentCount: comments.length, latestComments: comments.slice(-3) };
console.log('hybrid document  :', Buffer.byteLength(JSON.stringify(hybrid)), 'bytes with a counter and 3 comments');

This is a teaching simulation with plain arrays, not a MongoDB test (no server was used). The sizes are JSON approximations of document size. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): embedded model : reads = 1 | comments loaded = 1000 referenced model : reads = 2 | comments loaded = 10 (paged) one comment is about 86 bytes the 16 MiB limit is reached after about 195000 comments rewriting a document with 1000 comments moves about 89 KiB per update of the post hybrid document : 360 bytes with a counter and 3 comments

Key points

  • Model around access patterns.
  • Embed bounded data that is read with its parent.
  • Reference large, unbounded or shared data.
  • A document is limited to 16 MiB, so avoid unbounded arrays.
  • Compound indexes follow equality, sort, range.

Common mistakes

  • Embedding an array that grows forever.
  • Normalising everything like a relational database and then needing many lookups.
  • Copying data everywhere and never updating the copies.
  • Creating indexes for every field.
  • Designing the model before knowing the queries.

Follow-ups

  • What is the ESR rule for compound indexes?
  • How does the bucket pattern help time series data?
  • When do you use a multi-document transaction in MongoDB?

Tips

  • Start with 'access patterns'.
  • Give one example of each choice.
  • Mention the 16 MiB limit.