MongoDB โ Upsert Operations & FindAndModify
Master atomic upsert operations ({ upsert: true }), $setOnInsert, and thread-safe findOneAndUpdate() workflows for concurrent systems.
1What is an Upsert Operation?
An Upsert (Update + Insert) is a conditional atomic operation: if a document matching the query filter exists, MongoDB updates it; if no document matches, MongoDB automatically creates and inserts a new document combining the query filter and update modifiers.
Upsert Syntax Example
db.page_views.updateOne(
{ pageUrl: "/blog/mongodb" },
{
$inc: { views: 1 },
$setOnInsert: { firstVisited: new Date() } // Executed ONLY on new insert!
},
{ upsert: true }
);
2Atomic Read-and-Modify with findOneAndUpdate()
Standard updateOne() returns only write acknowledgment stats. When you need to retrieve the modified document atomically in a single step (e.g. reserving a seat or generating auto-increment sequence numbers), use findOneAndUpdate():
Atomic Counter Generator Example
async function getNextSequenceValue(sequenceName) {
const result = await db.counters.findOneAndUpdate(
{ _id: sequenceName },
{ $inc: { seq: 1 } },
{ returnDocument: "after", upsert: true }
);
return result.seq;
}