MongoDB Collections Interview Questions

Introduction

This guide covers essential MongoDB collections concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.

Easy

1. What is a Collection in MongoDB?

A collection in MongoDB is a group of documents, similar to a table in relational databases. Key characteristics include:

  • Schema-less design
  • Dynamic document structure
  • Automatic creation
  • Namespace organization
Collection Features:
  • No schema enforcement
  • Flexible document structure
  • Efficient querying
  • Index support
Medium

2. How do you create and manage collections?

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")
Medium

3. What are capped collections?

Capped collections are fixed-size collections that maintain insertion order. Key features include:

  • Fixed size
  • Automatic removal of oldest documents
  • High-performance writes
  • Natural ordering
// 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" }
])
Hard

4. How do you handle collection sharding?

Collection sharding in MongoDB involves:

  • Choosing a shard key
  • Enabling sharding
  • Managing data distribution
  • Monitoring shard balance
// 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()
Medium

5. What are the best practices for collection design?

Key best practices for MongoDB collection design include:

  • Collection Naming: Use meaningful names
  • Document Structure: Plan for query patterns
  • Indexing: Create appropriate indexes
  • Sharding: Choose proper shard keys
// 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 })
Hard

6. How do you handle collection validation?

MongoDB provides schema validation for collections through:

  • JSON Schema validation
  • Validation rules
  • Validation levels
  • Validation actions
// 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"
})

Next Steps

Continue your MongoDB interview preparation with: