MongoDB โ€” Upsert Operations & FindAndModify

๐Ÿƒ MongoDB 7.0+ ๐ŸŸข Chapter 22 of 50 ๐Ÿ“‚ Phase 05: Array Updates, Upserts & Deletions ๐Ÿ“… 2026 Edition

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;
}
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on MongoDB 7.0+ Standards ยท Last updated August 2026