This guide covers essential MongoDB CRUD operations commonly asked in technical interviews. Each question includes detailed answers and practical examples.
CRUD operations in MongoDB are:
Create operations in MongoDB can be performed using:
// 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" }
})
// 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" }
})
Read operations in MongoDB can be performed using:
// 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" })
// 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" } })
Update operations in MongoDB can be performed using:
// 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 }
)
// 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() }
}
)
Delete operations in MongoDB can be performed using:
// Delete one document
db.users.deleteOne({ email: "john@example.com" })
// Delete with options
db.users.deleteOne(
{ email: "john@example.com" },
{ writeConcern: { w: "majority" } }
)
// 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) } }
]
})
Best practices for CRUD operations include:
// 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();
}
Continue your MongoDB interview preparation with: