watch() (Watch Collection Changes)
Last updated: 2026-10-09
watch() (Watch Collection Changes)
watch() monitors a collection for changes and returns a Change Stream, e.g. `db.users.watch([{ $match: { 'operationType': 'insert' } }])`. Every insert, update, delete, or replace emits a change event. It requires a replica set or sharded cluster — standalone servers do not support it. Typical uses include real-time sync, cache invalidation, and audit logging.
| Category | Index & Admin |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.watch(<pipeline>, { fullDocument: 'updateLookup' })
⚙️ Parameters
| pipeline | Optional. Aggregation pipeline filtering change events. |
|---|---|
| fullDocument | Optional. 'updateLookup' attaches the full document to update events. |
Returns:A Change Stream cursor to iterate or listen on.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// watch: listen for inserts into users
const stream = db.users.watch([
{ $match: { 'operationType': 'insert' } }
])
stream.forEach(ev => print('New user: ' + ev.fullDocument.name))
Output:
New user: Alice
New user: Bob
📌 Notes
- Replica sets and sharded clusters only — not available on standalone
- Change events are persisted server-side in the oplog
- Make handlers idempotent in case events are redelivered
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QDoes watch work on a standalone MongoDB?
ANo — watch() needs a replica set or sharded cluster; it errors on a standalone deployment.
QCan watch listen only to inserts?
AYes — filter with a pipeline: db.users.watch([{$match: {'operationType': 'insert'}}]).
QWhat are watch() typical use cases?
AReal-time sync, cache invalidation, audit logging, and event-driven flows that must react to data changes.