Document Schema Design
Implement or sketch code for Document Schema Design. Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Audio N/AQuick interview answer
Logic: Embed when data accessed together and bounded size; reference when unbounded growth or shared entities. Balance read patterns vs write amplification.
Detailed answer
Logic: Embed when data accessed together and bounded size; reference when unbounded growth or shared entities. Balance read patterns vs write amplification. Complexity notes included in code section when present. Pros: Flexible schema evolves without migrations; embed reduces joins. Cons: Unbounded arrays hit 16MB doc limit; duplicate data needs sync strategy. Core: Embed when data accessed together and bounded size; reference when unbounded growth or shared entities. Balance read patterns vs write amplification. Real-time example: Order embeds line items array; Product referenced by id when catalog shared across orders. Pros: Flexible schema evolves without migrations; embed reduces joins. Cons: Unbounded arrays hit 16MB doc limit; duplicate data needs sync strategy. Common mistakes: Deep nesting mirroring relational 3NF; giant embedded arrays. Best practices: Design for queries; use schema validation; monitor document size. Audience level: Fresher.
Full explanation
Embed when data accessed together and bounded size; reference when unbounded growth or shared entities. Balance read patterns vs write amplification.
Real example & use case
Order embeds line items array; Product referenced by id when catalog shared across orders.
Pros & cons
Pros: Flexible schema evolves without migrations; embed reduces joins. Cons: Unbounded arrays hit 16MB doc limit; duplicate data needs sync strategy.
Code example
// Embedded line items — read order with items in one query
db.orders.insertOne({
_id: ObjectId(),
customerId: 'c1',
items: [
{ sku: 'A1', qty: 2, price: 19.99 },
{ sku: 'B2', qty: 1, price: 9.50 }
],
total: 49.48,
status: 'PAID'
});Practice code · javascript (view only · no execution)
// Embedded line items — read order with items in one query
db.orders.insertOne({
_id: ObjectId(),
customerId: 'c1',
items: [
{ sku: 'A1', qty: 2, price: 19.99 },
{ sku: 'B2', qty: 1, price: 9.50 }
],
total: 49.48,
status: 'PAID'
});Common mistakes
Deep nesting mirroring relational 3NF; giant embedded arrays.
Best practices
Design for queries; use schema validation; monitor document size.
Follow-up questions
- How would you test Document Schema Design?
- What metrics prove Document Schema Design is healthy in prod?
- How does Document Schema Design change at 10× traffic?