A document update is atomic, allowing related fields to change together. Multi-document invariants need an additional coordination strategy.
Before you start
You should understand documents, collections and indexes. Sketch representative documents and the reads and writes they must support. MongoDB-specific examples assume a collection with the shown fields; deployment topology, permissions and existing indexes can affect the operational behavior being discussed.
The practical goal is to reason through this situation: Increment stock and update its timestamp within one document operation. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: State the stock invariant
Quantity must not fall below zero.
Step 2: Combine condition and update
Match sufficient stock and decrement in the same atomic document operation.
Step 3: Inspect the result
A nonmatching update means availability was not established for that request.
Worked scenario
Increment stock and update its timestamp within one document operation.
db.products.updateOne(
{ _id: productId, stock: { $gte: requested } },
{ $inc: { stock: -requested } }
);Validate requested as a positive allowed quantity first. ProductId and requested are application inputs. Reading stock then writing a separately computed value creates a race the conditional update avoids.
Common mistake
Read-modify-write in application code can lose concurrent changes.
Verify the behavior
Submit competing decrements and assert successful outcomes never drive stock negative.
Interview exercise
Decrement stock only when available.
Answer and reasoning
Use a conditional atomic update matching sufficient stock and inspect the matched or modified result.
Continue learning
Compare the scenario with the MongoDB interview questions and test your understanding with the MongoDB MCQs. For terminology and implementation details, consult the reference material.