bulkWrite() — MongoDB Technical Interview Questions & Answers
Running many insert/update/delete ops in one round-trip.
bulkWrite()
- Simple meaning: bulkWrite sends many insert/update/delete operations in one round-trip.
- How to use: db.students.bulkWrite([ { insertOne: { document: { roll: 1 } } }, { updateOne: { filter: { roll: 2 }, update: { $set: { marks: 50 } } } } ]).
- ordered: true stops on first error.
- Try this: two operations in one bulkWrite, then find.
- Common mistake: a loop of insertOne in Node for 10,000 rows — slow. Use insertMany or bulkWrite.
- Interview tip: Batch writes. Fewer network hops.
Technical Interview Tip: bulkWrite vs a for-loop of insertOne.
Code Examples for bulkWrite()
bulkWrite() — working example
db.users.bulkWrite([
{ insertOne: { document: { name: "Riya", email: "riya@example.com", city: "Pune" } } },
{ updateOne: { filter: { email: "ada@example.com" }, update: { $set: { role: "admin" } } } },
{ deleteOne: { filter: { email: "lin@example.com" } } }
])bulkWrite() — bulkWrite batches many write operations in one round-trip.
How to Explain bulkWrite() to an Interviewer
Why bulkWrite?
Many writes in one round-trip