How do you model relationships in MongoDB: embedding vs referencing?

IntermediateConceptMongoDB
Answer

Short answer

Embedding puts related data inside the document (an order contains its line items). Referencing stores an id pointing to another document (an order stores customerId). Embed data that's read together and owned by the parent; reference data that's large, shared or grows without limit.

Embedding

{ _id: 1, customer: "Asha", items: [ { sku: "LAP-1", qty: 1, price: 52000 }, { sku: "MOU-2", qty: 1, price: 899 } ] }

✅ One read gets everything, atomic updates on one document. ❌ Document can grow too big (16 MB limit); duplicated data if shared.

Referencing

{ _id: 1, customerId: ObjectId("..."), total: 52899 }
{ _id: ObjectId("..."), name: "Asha", email: "[email protected]" }

✅ No duplication, unbounded relationships. ❌ Needs a second query or $lookup.

Rule of thumb

Relationship Usually
One-to-few, read together (address, line items) Embed
One-to-many large / unbounded (user → logs) Reference
Many-to-many (students ↔ courses) Reference (arrays of ids)

What to say in the interview

"Model for your queries: embed what's read together and bounded, reference what's shared, large or unbounded. Embedding gives single-read atomic updates; referencing avoids duplication and the 16 MB limit."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB