Problem Statement
What is the advantage of using bulkWrite() over multiple individual write operations?
Explanation
The bulkWrite method allows you to perform multiple write operations in a single request, significantly reducing network overhead. Instead of making multiple round trips to the database, you send all operations at once.
BulkWrite supports insertOne, updateOne, updateMany, deleteOne, deleteMany, and replaceOne operations in a single call. You can specify ordered execution where operations stop on first error, or unordered execution where all operations are attempted regardless of errors.
Code Solution
SolutionRead Only
// Bulk write with multiple operations
db.users.bulkWrite([
{
insertOne: {
document: { name: "Alice", age: 30 }
}
},
{
updateOne: {
filter: { name: "Bob" },
update: { $set: { age: 35 } }
}
},
{
deleteOne: {
filter: { name: "Charlie" }
}
},
{
replaceOne: {
filter: { name: "David" },
replacement: { name: "David", age: 40, city: "NYC" }
}
}
], { ordered: false })
// Result includes counts
{
insertedCount: 1,
matchedCount: 2,
modifiedCount: 2,
deletedCount: 1
}