{"success":true,"name":"use-mongodb-atomic-update-operators-instead-of-read-modify-w","description":"Updating a MongoDB document by reading it, changing it, then saving","category":"ai-brimind","path":"ai-brimind/use-mongodb-atomic-update-operators-instead-of-read-modify-w/SKILL.md","file":"SKILL.md","content":"---\nname: use-mongodb-atomic-update-operators-instead-of-read-modify-w\ndescription: \"Updating a MongoDB document by reading it, changing it, then saving\"\n---\n\n# Use MongoDB Atomic Update Operators Instead of Read-Modify-Write\n\n## When to use\nProject uses MongoDB, and you are about to fetch a document, modify it in JS, and save it back.\n\n## Example request\nIncrementing a counter with find → doc.count++ → save → two users at once lose an increment; $inc does it atomically in one operation. Adding an item to a list in JS then saving → $push/$addToSet does it server-side without a race. Toggling a flag after reading it → findOneAndUpdate with a filter on the current value makes check-and-set atomic. 'Create if missing, else update' in two queries → upsert:true is the built-in for exactly this. Each maps to 'MongoDB already has an atomic operator for that'.\n\n## Instructions\nAct as a concurrency-aware developer who treats every read-modify-write on MongoDB as a race condition until proven otherwise. Before writing fetch → change → save code: (1) name what the change actually is (increment, append, set-if, remove-from-list), (2) check MongoDB's built-in atomic operators first — $inc, $set, $push, $pull, $addToSet, $min/$max, and findOneAndUpdate with upsert — one of them almost always covers it in a single atomic operation, (3) if a check must happen before the write (only update if status is 'pending'), put the check INSIDE the filter so the test-and-set is one operation, not two. Reserve full read-modify-write for cases where complex logic truly needs the whole document, and say so explicitly. If unsure whether concurrent access can happen, assume it can. Only write the update once the atomic path is confirmed or ruled out, and explain why the operation is safe under two simultaneous users, not just correct for one.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1046\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}