MongoDB CRUD Operations Interview Questions

Introduction

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

Easy

1. What are CRUD operations in MongoDB?

CRUD operations in MongoDB are:

  • Create: Insert new documents
  • Read: Query and retrieve documents
  • Update: Modify existing documents
  • Delete: Remove documents
Basic CRUD Methods:
  • Create: insertOne(), insertMany()
  • Read: find(), findOne()
  • Update: updateOne(), updateMany()
  • Delete: deleteOne(), deleteMany()
Medium

2. How do you perform Create operations in MongoDB?

Create operations in MongoDB can be performed using:

1. Single Document Insertion
// Insert a single document
db.users.insertOne({
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    createdAt: new Date()
})

// Insert with options
db.users.insertOne({
    name: "Jane Doe",
    email: "jane@example.com"
}, {
    writeConcern: { w: "majority" }
})
2. Multiple Document Insertion
// Insert multiple documents
db.users.insertMany([
    {
        name: "Alice",
        email: "alice@example.com",
        age: 25
    },
    {
        name: "Bob",
        email: "bob@example.com",
        age: 35
    }
], {
    ordered: true,
    writeConcern: { w: "majority" }
})
Medium

3. How do you perform Read operations in MongoDB?

Read operations in MongoDB can be performed using:

1. Basic Queries
// Find all documents
db.users.find()

// Find with filter
db.users.find({ age: { $gt: 25 } })

// Find with projection
db.users.find(
    { age: { $gt: 25 } },
    { name: 1, email: 1, _id: 0 }
)

// Find one document
db.users.findOne({ email: "john@example.com" })
2. Advanced Queries
// Complex conditions
db.users.find({
    $and: [
        { age: { $gt: 25 } },
        { age: { $lt: 50 } },
        { status: "active" }
    ]
})

// Text search
db.users.find(
    { $text: { $search: "john" } },
    { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
Hard

4. How do you perform Update operations in MongoDB?

Update operations in MongoDB can be performed using:

1. Single Document Update
// Update one document
db.users.updateOne(
    { email: "john@example.com" },
    {
        $set: { status: "inactive" },
        $inc: { loginAttempts: 1 },
        $currentDate: { lastModified: true }
    }
)

// Update with options
db.users.updateOne(
    { email: "john@example.com" },
    { $set: { status: "active" } },
    { upsert: true }
)
2. Multiple Document Update
// Update many documents
db.users.updateMany(
    { status: "inactive" },
    {
        $set: { status: "active" },
        $currentDate: { lastModified: true }
    }
)

// Update with array operators
db.users.updateMany(
    { "roles": "user" },
    {
        $addToSet: { roles: "premium" },
        $set: { premiumSince: new Date() }
    }
)
Medium

5. How do you perform Delete operations in MongoDB?

Delete operations in MongoDB can be performed using:

1. Single Document Deletion
// Delete one document
db.users.deleteOne({ email: "john@example.com" })

// Delete with options
db.users.deleteOne(
    { email: "john@example.com" },
    { writeConcern: { w: "majority" } }
)
2. Multiple Document Deletion
// Delete many documents
db.users.deleteMany({ status: "inactive" })

// Delete with complex conditions
db.users.deleteMany({
    $and: [
        { status: "inactive" },
        { lastLogin: { $lt: new Date(Date.now() - 30*24*60*60*1000) } }
    ]
})
Hard

6. What are the best practices for CRUD operations?

Best practices for CRUD operations include:

  • Using appropriate write concerns
  • Implementing proper error handling
  • Optimizing query performance
  • Managing transactions
// Best practice: Using write concerns
db.users.insertOne({
    name: "John Doe",
    email: "john@example.com"
}, {
    writeConcern: { w: "majority", wtimeout: 5000 }
})

// Best practice: Error handling
try {
    const result = await db.users.updateOne(
        { email: "john@example.com" },
        { $set: { status: "active" } }
    );
    if (result.modifiedCount === 0) {
        console.log("No document was modified");
    }
} catch (error) {
    console.error("Error updating document:", error);
}

// Best practice: Using transactions
const session = client.startSession();
try {
    session.startTransaction();
    await db.users.updateOne(
        { email: "john@example.com" },
        { $set: { status: "inactive" } },
        { session }
    );
    await db.logs.insertOne({
        action: "deactivate",
        userId: "john@example.com",
        timestamp: new Date()
    }, { session });
    await session.commitTransaction();
} catch (error) {
    await session.abortTransaction();
    throw error;
} finally {
    session.endSession();
}

Next Steps

Continue your MongoDB interview preparation with: