{"success":true,"name":"use-mongodb-change-streams-instead-of-polling-for-changes","description":"Code repeatedly queries MongoDB to detect new or changed documents","category":"ai-brimind","path":"ai-brimind/use-mongodb-change-streams-instead-of-polling-for-changes/SKILL.md","file":"SKILL.md","content":"---\nname: use-mongodb-change-streams-instead-of-polling-for-changes\ndescription: \"Code repeatedly queries MongoDB to detect new or changed documents\"\n---\n\n# Use MongoDB Change Streams Instead of Polling for Changes\n\n## When to use\nProject uses MongoDB (replica set/Atlas), and a feature polls a collection on a timer to react to changes.\n\n## Example request\nsetInterval querying for new orders every 5 seconds → collection.watch() pushes changes the moment they happen. Syncing a cache by re-reading everything each minute → a change stream delivers just the deltas. Notifying users on new messages via polling → watch with a $match pipeline filters to only relevant events. Stream dies on network hiccup → resume tokens exist for exactly this; store and resume, don't restart blind. Each maps to 'the database can push — polling is reinventing notification badly'.\n\n## Instructions\nAct as a developer who treats a polling loop against MongoDB as a placeholder for the real mechanism. When code needs to react to data changes: (1) confirm the environment supports change streams (replica set or Atlas — standalone servers do not), (2) replace the poll with collection.watch() or db.watch(), adding a $match pipeline stage so you receive only the operation types and documents the feature cares about, and use fullDocument: 'updateLookup' when handlers need the whole updated document, (3) design for the stream's real failure modes before shipping: handle disconnects by persisting the resume token and resuming from it, so no events are lost during restarts — a change stream without resume handling is a demo, not a feature, (4) keep polling only when it is genuinely the right fit (standalone Mongo, very infrequent checks, batch-oriented logic) and state that reason. If the reaction latency requirement is unclear ('how fresh must this be?'), ask, because the answer picks the mechanism. Only implement once push-vs-poll is decided on evidence, and explain why the feature now reacts to events instead of burning queries to discover them.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1147\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}