What are the considerations for embedding vs. referencing documents in MongoDB?

Instruction: Compare and contrast the considerations for when to embed documents directly versus referencing them in MongoDB.

Context: This question revisits the topic of embedding vs. referencing documents in MongoDB, asking for a deeper analysis of the considerations affecting this design choice.

Updated

Official answer

Compare the aggregate's ownership, growth and update pattern. Embedding is useful for bounded data commonly read with its parent and changed atomically with it. Referencing is useful for independently managed entities, unbounded relationships or shared facts that should have one authoritative version.

For an order, embed the purchased line-item price/name snapshot because it records historical terms. Reference the current product for catalog navigation. The snapshot should not automatically change when the current catalog price changes. Store an unbounded review history separately.

MongoDB supports native aggregation joins through $lookup; referencing does not always require manual application joins. Joins still have index, fan-out and memory costs, so measure them. A reference can use a suitable identifier type, not only ObjectId, and it does not automatically enforce a foreign key.

Embedding can create large or hot documents and duplicated updates. Referencing can require more reads and cross-document coordination. Respect the 16 MiB document limit, define missing/deleted-reference behavior and use supported transactions where a required invariant spans documents.

Choose a hybrid model when appropriate, then test complete read/write workflows and failure cases rather than optimizing one query in isolation.

MongoDB lookup, data modeling

Related Questions