Q1. How do you create (insert) documents in MongoDB?
With MongoDB driver:
const result = await db.collection('users').insertOne({
name: 'John',
age: 30
});
For multiple: insertMany([...]). With Mongoose:
const user = new User({ name: 'John' });
await user.save();
or
User.create({ name: 'John' });
The inserted document includes an _id field automatically.Q2. How do you read (query) documents?
With MongoDB driver:
const users = await db.collection('users')
.find({ age: { $gt: 18 } })
.toArray();
For single: findOne({ _id: ObjectId(id) }). With Mongoose:
const users = await User.find({ age: { $gt: 18 } });
const user = await User.findById(id);
Queries support filtering, projection, sorting, and pagination.Q3. How do you update documents?
With MongoDB driver:
await db.collection('users').updateOne(
{ _id: id },
{ $set: { age: 31 } }
);
For multiple: updateMany(). With Mongoose:
await User.updateOne(
{ _id: id },
{ $set: { age: 31 } }
);
or find and update:
await User.findByIdAndUpdate(id, { age: 31 }, { new: true });
The $set operator updates specific fields.Q4. How do you delete documents?
With MongoDB driver:
await db.collection('users').deleteOne({ _id: id });
or deleteMany(). With Mongoose:
await User.deleteOne({ _id: id });
or
await User.findByIdAndDelete(id);
Be careful with delete operations as they are irreversible. Consider soft deletes by adding a deleted flag instead.Q5. How do you handle errors in CRUD operations?
Use try/catch blocks. Common errors: duplicate key (E11000), validation errors, cast errors (invalid ObjectId), connection errors. Example:
try {
await user.save();
} catch (err) {
if (err.code === 11000) {
// duplicate key error
} else {
// handle other errors
}
}
Always send appropriate HTTP status codes.