What are the differences between embedding and referencing documents in MongoDB?

Instruction: Compare and contrast embedding and referencing documents, including when to use each approach.

Context: This question is designed to assess the candidate's ability to design efficient MongoDB schemas by leveraging embedding and referencing based on the relationships between data entities.

Updated

Official answer

Embedding stores related values inside a parent document; referencing stores an identifier that points to another document. Choose from ownership, access patterns, update frequency and cardinality, rather than treating one approach as universally faster.

Embed a bounded address snapshot or a small set of line items when it belongs to one aggregate and is usually read with it. A single-document update is atomic. Duplicated values still need a deliberate rule: an order's historical shipping address may intentionally remain unchanged when the customer's current address changes.

Reference independently managed or unbounded entities, such as many reviews for a product. Keep appropriate indexes for lookups and use aggregation joins or application queries when needed. A reference may use an ObjectId or another chosen identifier type; storing the identifier does not automatically enforce a foreign-key constraint or cascade deletion.

Plan integrity explicitly. Coordinate required cross-document changes through supported transactions or an appropriate consistency/reconciliation workflow. Test deletion, missing references and concurrent updates. Avoid indefinitely growing arrays and respect MongoDB's 16 MiB document limit.

Measure reads, writes, document growth and duplication costs on representative data. A model that minimizes one query's round trips can still cause expensive updates or hot documents elsewhere.

MongoDB data modeling, transactions, document limits

Related Questions