Data Modeling in MongoDB — MongoDB Technical Interview Questions & Answers
Embedding vs referencing related data.
Data Modeling in MongoDB
- Simple meaning: Decide if related data lives inside the same document (embed) or in another collection with an id (reference).
- Embed: { name: "Asha", address: { city: "Pune" } } — good for 1-to-few data you always read together.
- Reference: student has courseIds: ["c1","c2"] and courses live in another collection — good when lists grow large or are shared.
- Try this: embed city. Do not embed 10,000 attendance rows inside one student (document grows, 16MB limit).
- Common mistake: copying six SQL tables into six collections and joining everything. Start from the screen: what do you load together?
- Interview tip: Embed small + owned. Reference large + shared. Mention the 16MB document cap.
Technical Interview Tip: Embed vs reference + one student example.
Code Examples for Data Modeling in MongoDB
Data Modeling in MongoDB — 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" } }
])Data Modeling in MongoDB — embed for data read together; reference when related data is shared or grows without bound.
How to Explain Data Modeling in MongoDB to an Interviewer
Embed or reference?
Embed small data you always load with the parent Reference when the array would grow huge