Upserts and findOneAndUpdate
An upsert is an update that inserts a new document when nothing matches. It answers a very common need, "update the record if it exists, otherwise create it", in one atomic operation instead of a find followed by an insert (which can race with another client doing the same thing).
upsert: true
Add { upsert: true } as the third argument of updateOne, updateMany or replaceOne:
// product 21 doesn't exist: it is inserted
const first = db.products.updateOne(
{ _id: 21 },
{ $set: { name: 'Matcha Powder', category: 'tea', price: 22 } },
{ upsert: true }
);
print(first);
// the second time it exists: it is updated
const second = db.products.updateOne(
{ _id: 21 },
{ $set: { name: 'Matcha Powder', category: 'tea', price: 20 } },
{ upsert: true }
);
print(second.matchedCount, second.modifiedCount, second.upsertedCount);
print(db.products.findOne({ _id: 21 }));{
acknowledged: true,
insertedId: 21,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1
}
1 1 0
{ _id: 21, category: 'tea', name: 'Matcha Powder', price: 20 }
On insert, the new document is built from the equality conditions of the filter (_id: 21) plus the fields of the update.
$setOnInsert: values only for new documents
Some fields should be written only when the document is created, such as a creation date or a starting counter. $setOnInsert does exactly that and is ignored on updates:
function recordView(productId) {
db.views.updateOne(
{ _id: productId },
{
$inc: { count: 1 },
$setOnInsert: { firstSeen: ISODate('2026-06-10T09:00:00Z') }
},
{ upsert: true }
);
}
recordView(3);
recordView(3);
recordView(12);
recordView(3);
print(db.views.find().sort({ _id: 1 }).toArray());[
{ _id: 3, count: 3, firstSeen: ISODate('2026-06-10T09:00:00.000Z') },
{ _id: 12, count: 1, firstSeen: ISODate('2026-06-10T09:00:00.000Z') }
]
This counter pattern is a favourite use of upserts: no "does it exist yet?" check is needed.
Upserts with operator filters
If the filter uses operators such as $gt, those conditions can't be copied into the new document. Only the equality parts are:
const r = db.products.updateOne(
{ name: 'Hojicha', price: { $gt: 100 } },
{ $set: { category: 'tea', stock: 10 } },
{ upsert: true }
);
print(db.products.findOne({ _id: r.insertedId }, { _id: 0 }));{ name: 'Hojicha', category: 'tea', stock: 10 }
No _id was given, so MongoDB generated an ObjectId (mongosh reports it as insertedId in the result); we printed the document without it, because it differs on every run.
Warning: Upsert on a field without a unique index can create duplicates when two clients upsert the same new value at the same moment. Filter on
_idor on a field with a unique index.
findOneAndUpdate
updateOne tells you how many documents changed. findOneAndUpdate returns the document itself, before or after the change, in one atomic step:
| Option | Meaning |
|---|---|
returnDocument: 'before' |
return the document as it was (default) |
returnDocument: 'after' |
return the updated document |
projection |
which fields to return |
sort |
which document to pick when several match |
upsert |
insert if nothing matches |
A classic use is generating sequential numbers, such as invoice numbers:
function nextInvoiceNumber() {
const counter = db.counters.findOneAndUpdate(
{ _id: 'invoice' },
{ $inc: { seq: 1 } },
{ upsert: true, returnDocument: 'after' }
);
return 'INV-' + String(counter.seq).padStart(5, '0');
}
print(nextInvoiceNumber());
print(nextInvoiceNumber());
print(nextInvoiceNumber());INV-00001
INV-00002
INV-00003
Reserving stock is another: decrement only if enough units are left, and get the result back:
function reserve(productId, qty) {
const before = db.products.findOneAndUpdate(
{ _id: productId, stock: { $gte: qty } },
{ $inc: { stock: -qty } },
{ projection: { name: 1, stock: 1 } }
);
return before ? `reserved ${qty} x ${before.name} (had ${before.stock})` : 'not enough stock';
}
print(reserve(13, 3));
print(reserve(13, 3));reserved 3 x Gooseneck Kettle (had 4)
not enough stock
The filter stock: { $gte: qty } makes the check and the decrement a single atomic operation, so stock can never go negative.
Test yourself
What happens when an updateOne with upsert: true matches no document?
- Nothing
- An error is thrown
- A new document is inserted, built from the filter's equality fields and the update
- The whole collection is updated
When is $setOnInsert applied?
- On every update
- Only when an upsert inserts a new document
- Only on deletes
- Only with replaceOne
By default, what does findOneAndUpdate return?
- The document after the update
- The document before the update
- The number of modified documents
- Nothing