Upserts & Bulk Writes
Insert-or-update in one operation with upsert, and combine many operations efficiently with bulkWrite.
What Is an Upsert?
An upsert ("update or insert") updates a matching document if one exists, or inserts a brand-new one if it doesn't — a single operation covering both cases, useful for "create or refresh" logic like caching a computed value.
Using upsert: true
db.settings.updateOne( { userId: "u123" }, { $set: { theme: "dark" } }, { upsert: true },);// If a settings document for u123 exists, its theme is updated.// If not, a new one is created with { userId: "u123", theme: "dark" }.Combine upsert with $setOnInsert to set fields only when a new document is actually being created, leaving them untouched on an existing document that's merely updated.
db.settings.updateOne( { userId: "u123" }, { $set: { theme: "dark" }, $setOnInsert: { createdAt: new Date() }, // only set if this creates a new document }, { upsert: true },);bulkWrite
bulkWrite() sends a batch of different operations (inserts, updates, deletes) to the server in one round trip — far more efficient than issuing each one individually over the network.
db.products.bulkWrite([ { insertOne: { document: { name: "Keyboard", price: 45 } } }, { updateOne: { filter: { name: "Mouse" }, update: { $set: { price: 20 } } } }, { deleteOne: { filter: { name: "Discontinued Item" } } },]);Ordered vs Unordered Bulk Writes
By default, bulkWrite() executes operations in order and stops at the first failure. Passing { ordered: false } executes all operations regardless of individual failures, reporting every error at the end instead.
db.products.bulkWrite(operations, { ordered: false });FAQs
Yes — the check-and-insert-or-update happens as a single atomic operation on the server, avoiding a race condition between checking existence and acting on it.
Whenever you have many operations to perform together — batch imports, syncing external data — bulkWrite dramatically reduces network round trips compared to looping over individual insert/update/delete calls.
Summary
Upserts collapse "create or update" logic into one atomic operation, and bulkWrite batches many operations efficiently. With core CRUD covered, the next section moves into schema design — the most important skill for using MongoDB well.