This guide covers essential MongoDB schema design concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.
Key considerations in MongoDB schema design include:
Common MongoDB schema patterns include:
// User with embedded address
{
_id: ObjectId("..."),
name: "John Doe",
email: "john@example.com",
address: {
street: "123 Main St",
city: "New York",
state: "NY",
zip: "10001"
}
}
// Order with embedded items
{
_id: ObjectId("..."),
orderNumber: "ORD123",
customerId: "CUST456",
items: [
{
productId: "PROD1",
name: "Laptop",
quantity: 1,
price: 999.99
},
{
productId: "PROD2",
name: "Mouse",
quantity: 2,
price: 29.99
}
]
}
MongoDB supports several relationship patterns:
// One-to-One: Embedded Document
{
_id: ObjectId("..."),
name: "John Doe",
passport: {
number: "P123456",
expiryDate: ISODate("2025-12-31")
}
}
// One-to-Many: Reference Pattern
// Parent document
{
_id: ObjectId("..."),
name: "Department A",
employees: [
ObjectId("emp1"),
ObjectId("emp2")
]
}
// Child documents
{
_id: ObjectId("emp1"),
name: "Employee 1",
departmentId: ObjectId("...")
}
// Many-to-Many: Array of References
{
_id: ObjectId("..."),
name: "Project X",
teamMembers: [
ObjectId("emp1"),
ObjectId("emp2"),
ObjectId("emp3")
]
}
Schema validation best practices include:
// Create collection with validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: {
bsonType: "string",
minLength: 2
},
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 120
},
address: {
bsonType: "object",
properties: {
street: { bsonType: "string" },
city: { bsonType: "string" },
zip: { bsonType: "string" }
}
}
}
}
},
validationLevel: "strict",
validationAction: "error"
})
Schema evolution strategies include:
// Versioning documents
{
_id: ObjectId("..."),
schemaVersion: 2,
name: "John Doe",
email: "john@example.com",
// New fields in version 2
phone: "+1234567890",
preferences: {
notifications: true,
theme: "dark"
}
}
// Migration script example
db.users.find({ schemaVersion: 1 }).forEach(function(doc) {
db.users.update(
{ _id: doc._id },
{
$set: {
schemaVersion: 2,
phone: "",
preferences: {
notifications: true,
theme: "light"
}
}
}
);
});
Schema optimization techniques include:
// Denormalized schema for read performance
{
_id: ObjectId("..."),
orderNumber: "ORD123",
customer: {
name: "John Doe",
email: "john@example.com",
address: "123 Main St"
},
items: [
{
productId: "PROD1",
name: "Laptop",
price: 999.99,
category: "Electronics"
}
],
totalAmount: 999.99,
status: "completed",
createdAt: ISODate("2025-01-01")
}
// Create appropriate indexes
db.orders.createIndex({ orderNumber: 1 })
db.orders.createIndex({ "customer.email": 1 })
db.orders.createIndex({ createdAt: -1 })
db.orders.createIndex({ status: 1, createdAt: -1 })
Continue your MongoDB interview preparation with: