Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / CRUD Operations with Node.js and MongoDB
interview

Q1. How do you insert a document using Node.js driver?
After connecting, get the collection and use insertOne():
const collection = db.collection('users'); const result = await collection.insertOne({ name: 'John', age: 30 }); console.log(result.insertedId);
For multiple:
await collection.insertMany([doc1, doc2]);

Q2. How do you query documents?
Use find() which returns a cursor:
const cursor = collection.find({ age: { $gt: 25 } }); const users = await cursor.toArray();
For a single document:
const user = await collection.findOne({ name: 'John' });

Q3. How do you update documents?
Use updateOne() or updateMany():
await collection.updateOne( { name: 'John' }, { $set: { age: 31 } } ); await collection.updateMany( { age: { $lt: 18 } }, { $set: { status: 'minor' } } );

Q4. How do you delete documents?
Use deleteOne() or deleteMany():
await collection.deleteOne({ name: 'John' }); await collection.deleteMany({ status: 'inactive' });
Check result.deletedCount to see how many were deleted.

Q5. How do you handle ObjectId in Node.js?
Import ObjectId from mongodb:
const { ObjectId } = require('mongodb'); const id = new ObjectId("507f1f77bcf86cd799439011"); const user = await collection.findOne({ _id: id });
Always validate ObjectId strings to avoid cast errors.