Consider a MongoDB collection products with documents:
[{ _id: 1, name: "Pen", stock: 10 }, { _id: 2, name: "Pencil", stock: 5 }]What will be the result of this bulkWrite operation?
db.products.bulkWrite([
{ updateOne: { filter: { _id: 1 }, update: { $inc: { stock: 5 } } } },
{ updateOne: { filter: { _id: 2 }, update: { $set: { stock: 0 } } } }
])db.products.bulkWrite([
{ updateOne: { filter: { _id: 1 }, update: { $inc: { stock: 5 } } } },
{ updateOne: { filter: { _id: 2 }, update: { $set: { stock: 0 } } } }
])Each updateOne matches one document and modifies it.
Both updateOne operations match one document each (_id 1 and 2). Both modify the stock field, so nMatched and nModified are 2.
Choose the correct bulkWrite syntax to insert two new documents into a MongoDB collection.
The correct key for inserting a single document is insertOne with document field.
Option B uses the correct insertOne operation with document key. Options A and B use invalid keys. Option B mixes insertOne and insertMany which is valid in bulkWrite.
You want to insert 100 new documents and update 50 existing documents in one bulkWrite operation. Which approach is best for performance?
bulkWrite supports mixing different operation types in one call.
Option A uses one bulkWrite call with all operations mixed, reducing network overhead and improving performance. Options B and C cause multiple calls. Option A is invalid because updateMany cannot update different documents with different filters in one call.
Identify the syntax error in this bulkWrite command:
db.collection.bulkWrite([
{ updateOne: { filter: { _id: 1 }, update: { $set: { name: "X" } } } },
{ insertOne: { document: { name: "Y" } }
])db.collection.bulkWrite([
{ updateOne: { filter: { _id: 1 }, update: { $set: { name: "X" } } } },
{ insertOne: { document: { name: "Y" } }
])Check the braces and commas carefully in the array of operations.
The insertOne operation object is missing a closing brace '}', causing a syntax error. The comma between operations is present. $set is valid. bulkWrite can be used without callback in modern drivers.
You run a bulkWrite with ordered: false containing 10 operations. The 5th operation fails due to a duplicate key error. What is the behavior of the remaining operations?
Consider the difference between ordered and unordered bulkWrite behavior.
With ordered: false, bulkWrite continues executing all operations even if some fail. Only the failed operations are reported as errors. With ordered: true, execution stops at the first failure.