Overview
Change streams use the observer pattern to notify your application of data changes:- Insert - New document created
- Update - Existing document modified
- Delete - Document removed
Basic usage
Watch all changes
Subscribe to all changes in a collection.Watch with filter
Only receive events matching a query.Event types
Insert events
Triggered when a new document is created.Update events
Triggered when a document is modified.Delete events
Triggered when a document is removed.Filtering events
Simple filters
Use the query language to filter events.Delete events with filters are not sent because there’s no document to filter against.
Multiple watchers
You can have multiple watchers with different filters.Watch handle
TheWatchHandle uses RAII to automatically unsubscribe when dropped.
Automatic cleanup
Manual unsubscribe
Handle metadata
Real-world examples
Audit logging
Log all changes to sensitive collections.Cache invalidation
Invalidate cached data when underlying documents change.Real-time notifications
Send push notifications when data changes.Data synchronization
Sync changes to another database or service.Materialized views
Maintain derived data automatically.Performance considerations
Common patterns
Temporary watcher
Error handling
Multiple collections
Best practices
Next steps
CRUD operations
Operations that trigger events
Querying
Filter syntax for watchers
Aggregation
Analyze change stream events
Performance
Optimize event processing