MongoDb Change Streams


Why change streams

  1. In real time applications, when data changes (inserts or update or delete) in MongoDB by some other services.
  2. Now, whenever the data changes we need to update the UI or some other services react immediately
  3. MongoDB provides the same functionality with Change Streams.
  4. If you want event alert when some data modification is done on MongoDB, we need to use Change Streams provided by MongoDB.
  5. Change Streams introduced in mongo 3.6, before 3.6 we can get the latest updated date by looking into oplog capped collection (this collection stores every collection logs by date of modification) by using a tailable cursors (cursor without close, it will always open for latest changes).
  6. Change Streams are better than oplog tailable cursors.
  7. It also maintains the insertion order.

Syntax for Change Stream

const eventCursor = db.collection('users').watch();

Above query returns document whenever the collection 'users' changes, so it basically returns cursor without close.

Operation Types of Change Streams

  1. Insert
  2. Update
  3. Delete
  4. Replace - Replace everything except the primary key
  5. Invalidate - Not data change, changes on collection properties like a change in the collection name.