{"success":true,"name":"use-addtoset-slice-and-array-operators-for-mongodb-list-fiel","description":"Modifying an array field inside a MongoDB document from code","category":"ai-brimind","path":"ai-brimind/use-addtoset-slice-and-array-operators-for-mongodb-list-fiel/SKILL.md","file":"SKILL.md","content":"---\nname: use-addtoset-slice-and-array-operators-for-mongodb-list-fiel\ndescription: \"Modifying an array field inside a MongoDB document from code\"\n---\n\n# Use $addToSet, $slice and Array Operators for MongoDB List Fields\n\n## When to use\nProject uses MongoDB, and code adds, removes, or updates items inside a document's array field.\n\n## Example request\nChecking 'if not already in list' in JS then pushing → $addToSet does the uniqueness check atomically in one operation. Removing an item by fetching, filtering in JS, saving → $pull with a condition removes it server-side. Updating one item inside an array of objects → the positional $ operator (or arrayFilters for multiple matches) edits it in place. Keeping only the newest 10 entries → $push with $each + $slice caps the array in the same write. Each maps to 'MongoDB's array operators already implement the list logic you were about to code'.\n\n## Instructions\nAct as a developer who checks MongoDB's array operator toolbox before writing any JS that manipulates a document's array. When list logic appears: (1) name the operation in words — add-unique, remove-matching, update-one-element, cap-length, add-many — (2) map it to the built-in: $addToSet (unique add), $pull (conditional remove), $push with $each/$slice/$sort (append, cap, keep-sorted), positional $ and arrayFilters (edit elements in place), $elemMatch (query elements by multiple conditions), (3) prefer the operator because it is one atomic server-side operation — the fetch-edit-save version you were about to write both races under concurrency and moves the whole document over the wire, (4) if the logic seems too complex for operators, check arrayFilters and pipeline-style updates (update with aggregation) before concluding that, and only then fall back to read-modify-write with a stated reason. Only write the code once the operation is mapped to its operator or the fallback is justified, and explain why the array change is atomic and server-side rather than reimplemented in application code.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1059\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}