Skip to the page

NoSQL and MongoDB · mid

MongoDB data modelling: embed or reference

In MongoDB you model from the screens and queries. Data read together is stored together. What grows without limit goes in its own collection.

The notes

What you must know

  • MongoDB's rule: data that is read together is stored together. Start from the screens and the queries, not from tables.
  • Embed what belongs to the parent, is read with it and stays small: tags, or a copy of the author's name and avatar.
  • Reference what grows without limit or is read alone: comments in their own collection with a postId field.
  • A BSON document cannot be larger than 16 MiB. Very large arrays also hurt index performance, and MongoDB lists unbounded arrays as an anti-pattern.
  • Useful patterns: subset (embed the latest 10 comments), bucket (comments in groups of 100), computed (commentCount stored on the post), extended reference (a copied author name).
  • A copied field needs an update plan: a background job updates the name, or you accept old names on old comments.
  • Likes: a likes collection with a unique index on postId and userId, plus a counter on the post updated with $inc.
  • Heavy use of $lookup is a sign that the model fights the queries.

The red pen

Common traps: mistake → fix

  • Mistake: Put all comments in an array on the post

    Fix: it grows without limit and hits the 16 MiB limit.

  • Mistake: Normalise like SQL and join everywhere with $lookup

    Fix: you lose the reason for a document model.

  • Mistake: Copied data stays correct by itself

    Fix: you must plan how it is updated.

Easy to hard

Questions interviewers ask, easy to hard

  1. Model a blog with users, posts, comments and likes in MongoDB.
  2. What do you embed and what do you reference?
  3. What is the document size limit and why does it matter?
  4. Name two document design patterns.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview