Atomicity: why $inc beats read-modify-write
This is the interview question behind half the update operators. The guarantee is real but narrower than people assume, and knowing exactly where its edge is separates a confident answer from a hopeful one.
MongoDB guarantees that a single-document write operation is atomic.
Example:
db.accounts.updateOne(
{
_id: accountId,
balance: {
$gte: 100
}
},
{
$inc: {
balance: -100
}
}
)
This is powerful.
Imagine two requests try to withdraw money simultaneously.
Instead of:
1. Read balance
2. Check balance
3. Update balance
You combine the condition and update:
balance >= 100
+
decrement balance by 100
in one atomic operation.
That pattern is the standard answer to any interview question about two processes racing for the same document.
Try it
Same shape as above, on the sample data. Mouse has stock, so the decrement happens:
db.products.updateOne(
{
product: "Mouse",
inStock: { $gte: 1 }
},
{
$inc: { inStock: -1 }
}
)
Edit it to Laptop, which is out of stock, and you get matchedCount: 0. Nothing was read, checked and then written - the condition and the write were the same operation.