Q1. How do you create (insert) documents in MongoDB?
With MongoDB driver:
For multiple: insertMany([...]). With Mongoose:
The inserted document includes an _id field automatically.
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:
For single: findOne({ _id: ObjectId(id) }). With Mongoose:
Queries support filtering, projection, sorting, and pagination.
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:
For multiple: updateMany(). With Mongoose:
The $set operator updates specific fields.
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:
With Mongoose:
Be careful with delete operations as they are irreversible. Consider soft deletes by adding a deleted flag instead.
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:
Always send appropriate HTTP status codes.
Example:
try { await user.save(); } catch (err) { if (err.code === 11000) { // duplicate key } else { // handle other errors } }Always send appropriate HTTP status codes.
