intermediateTop 30 Scenario-Based Questions
How do you implement optimistic concurrency control in MongoDB?
Version-based optimistic concurrency: 1) Add version field to document: {_id, name, balance:1000, version:5}. 2) Read: fetch document including version. 3) Modify: calculate new balance. 4) Write with version check: result = db.accounts.updateOne({_id: id, version: 5}, {$set: {balance: 900}, $inc: {version: 1}}). 5) Check result.modifiedCount: if 0 → conflict (another process updated it) → re-read
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response