Embedding vs referencing in MongoDB

NoSQL and choosing a database Mid-level Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

A blog post can receive 50,000 comments. How do you store them?

Options
Hint 1 of 1

Is the list bounded?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Comments in their own collection referencing the post id, maybe embedding the latest few

Correct. Unbounded growth belongs outside the parent.

Embed what is bounded and read with the parent. Comments grow without limit, so they get their own collection keyed by post id, and the post can keep a few recent ones for fast display.

Why not the others?
  • B Embed all comments in the post document. Hits the 16 MB limit and makes every post read heavy.
  • C One document per post with comments as a single string. Unqueryable.
  • D Put comments in Redis only. Not durable.

30-second answer

Embed data that belongs to the parent, is read with it, and stays bounded: an order's line items, a user's addresses. Reference data that is shared, changes independently, or grows without limit: the product catalogue, or a post's comments once they can number in the thousands. Documents have a 16 MB limit, and updating one document is atomic, which is a strong reason to keep things that change together in one document.

Practise saying it · 30 s. No recording, just a timer

Embed or reference?

Say your answer out loud, then check which of these points you covered:

  • Embed owned, bounded, read-together
  • Reference shared or unbounded
  • 16 MB limit
  • Single-document atomicity

Deep dive

Patterns: subset (embed the latest 10 comments, reference the rest), extended reference (copy a few fields like product name).

Index the fields you query; unindexed queries scan collections.

Use schema validation ($jsonSchema) for required fields and types.

$lookup joins exist but are slower than embedding for hot paths.

Common mistakes

  • Unbounded arrays inside a document.
  • Embedding shared data and then updating thousands of copies.
  • No indexes on query fields.

Senior take & follow-ups

Embed bounded, owned, read-together data; reference shared or unbounded data; mention atomicity and the size limit.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's the document size limit?

    Show hint

    16 MB in MongoDB.

  2. What's an extended reference?

    Show hint

    Storing a few frequently read fields of the referenced document alongside the id.

Suggest a fix if something here is wrong or out of date.