A MongoDB application stores inventory documents in the 'inventory' collection with fields 'sku', 'on_hand', and 'reserved'. During a flash sale, many concurrent sessions must decrement 'on_hand' by 1 only when on_hand is greater than 0, and each successful decrement must return the resulting document to the client. Which approach guarantees this behavior?
findOneAndUpdate atomically matches the filter, applies the decrement, and returns the document. With returnDocument: 'after' the client receives the post-decrement state, and the on_hand: { $gt: 0 } filter prevents negative stock. This single atomic operation satisfies both the conditional decrement and the requirement to return the updated document.
Why this answer
findOneAndUpdate performs the conditional match, the $inc decrement, and the return of the document in one atomic operation. The on_hand: { $gt: 0 } filter guards against negative inventory under concurrency, and returnDocument: 'after' supplies the resulting state. Separating read and write, or using updateOne or bulkWrite, either introduces races or fails to return the document.
Exam trap
The trap here is assuming updateOne can return the modified document or that a separate find before an update is safe under concurrency.