{"success":true,"name":"use-mongodb-bulkwrite-instead-of-awaiting-writes-in-a-loop","description":"Looping over items and writing each one to MongoDB separately","category":"ai-brimind","path":"ai-brimind/use-mongodb-bulkwrite-instead-of-awaiting-writes-in-a-loop/SKILL.md","file":"SKILL.md","content":"---\nname: use-mongodb-bulkwrite-instead-of-awaiting-writes-in-a-loop\ndescription: \"Looping over items and writing each one to MongoDB separately\"\n---\n\n# Use MongoDB bulkWrite Instead of Awaiting Writes in a Loop\n\n## When to use\nProject uses MongoDB, and code performs many inserts/updates in a for-loop with one await per document.\n\n## Example request\nfor (item of items) await Model.updateOne(...) → 5,000 round trips; bulkWrite sends them as one batch. Importing a CSV row by row → insertMany inserts the whole batch in one call. Mixed operations (some insert, some update, some delete) → bulkWrite accepts all three types in a single ordered or unordered batch. One bad document aborting a whole import → ordered:false continues past failures and reports them at the end. Each maps to 'the driver batches for you — round trips are the real cost'.\n\n## Instructions\nAct as a developer who counts network round trips before counting lines of code. When code writes many documents to MongoDB: (1) recognize the smell — an await inside a loop means one round trip per document; at hundreds or thousands of items that dominates all other cost, (2) map the work to the built-in batch tools: insertMany for pure inserts, bulkWrite for mixed insert/update/delete operations, updateMany when one filter+change covers all documents, (3) choose the failure behavior deliberately: ordered:true stops at the first error (all-or-nothing feel), ordered:false processes everything and reports which items failed — for imports, unordered plus error reporting is usually what the user actually wants, (4) chunk very large batches (a few thousand ops per bulkWrite) to keep memory and payload sane. Keep the loop version only when each write truly depends on the previous write's result, and say so. Only ship the write path once it is batched or the dependency is justified, and explain why the operation now costs a handful of round trips instead of thousands.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1144\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}