Embedding vs Referencing — MongoDB Technical Interview Questions & Answers
Side-by-side comparison table.
Embedding vs Referencing
- Simple meaning: Embed copies related data inside the parent. Reference stores an id and loads the other collection when needed.
- Embed address in student. Reference courses if many students share a course catalog.
- 16MB limit and growing arrays push you to reference.
- Interview tip: Read pattern + growth. Give one embed and one reference example.
Technical Interview Tip: One embed example, one reference example.
Code Examples for Embedding vs Referencing
Embedding vs Referencing — working example
// Embedding (read locality):
db.orders.insertOne({
orderId: "O-100",
customer: { name: "Ada", email: "ada@example.com" },
items: [{ sku: "BOOK", qty: 2, price: 399 }]
})
// Referencing (avoid unbounded growth):
db.orders.insertOne({
orderId: "O-101",
customerId: ObjectId("507f1f77bcf86cd799439011"),
itemIds: [ObjectId("507f191e810c19729de860ea")]
})
// Then join when needed:
db.orders.aggregate([
{ $match: { orderId: "O-101" } },
{ $lookup: { from: "users", localField: "customerId", foreignField: "_id", as: "customer" } }
])Embedding vs Referencing — embed for data read together; reference when related data is shared or grows without bound.
How to Explain Embedding vs Referencing to an Interviewer
Embedding vs referencing?
Inside the same document vs id in another collection