This guide covers essential MongoDB collections concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.
A collection in MongoDB is a group of documents, similar to a table in relational databases. Key characteristics include:
MongoDB provides several ways to create and manage collections:
// Create a collection explicitly
db.createCollection("users", {
capped: true,
size: 1000000,
max: 1000
})
// Create collection implicitly
db.users.insertOne({
name: "John Doe",
email: "john@example.com"
})
// List all collections
show collections
// Drop a collection
db.users.drop()
// Rename a collection
db.users.renameCollection("customers")
Capped collections are fixed-size collections that maintain insertion order. Key features include:
// Create a capped collection
db.createCollection("logs", {
capped: true,
size: 1000000, // Size in bytes
max: 1000 // Maximum number of documents
})
// Insert documents
db.logs.insertMany([
{ timestamp: new Date(), message: "Log 1" },
{ timestamp: new Date(), message: "Log 2" }
])
Collection sharding in MongoDB involves:
// Enable sharding for database
sh.enableSharding("mydb")
// Shard a collection
sh.shardCollection("mydb.users", { userId: 1 })
// Check shard status
sh.status()
// Monitor shard distribution
db.users.getShardDistribution()
Key best practices for MongoDB collection design include:
// Good Practice: Meaningful Collection Names
db.user_profiles
db.order_items
db.product_categories
// Good Practice: Appropriate Indexes
db.users.createIndex({ email: 1 }, { unique: true })
db.orders.createIndex({ customerId: 1, orderDate: -1 })
// Good Practice: Shard Key Selection
sh.shardCollection("mydb.orders", { customerId: 1, orderDate: 1 })
MongoDB provides schema validation for collections through:
// Create collection with validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "must be a string"
},
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
},
age: {
bsonType: "int",
minimum: 0
}
}
}
},
validationLevel: "strict",
validationAction: "error"
})
Continue your MongoDB interview preparation with: