SyntaxStudy
Sign Up
MongoDB Beginner 1 min read

Change Streams

Change streams allow applications to subscribe to real-time notifications of changes to a collection, database, or entire deployment. They are built on MongoDB's oplog (operations log), which is the replication mechanism used internally. Change streams support resumability — if the connection drops, you can restart from a stored resume token and replay missed events without losing data. Each change event includes the operation type (insert, update, replace, delete), the document key, and for update events, an update description showing which fields were modified. Change streams are ideal for building event-driven microservices, cache invalidation systems, audit logs, and real-time dashboards.
Example
// Watch a collection for all changes
const collection = client.db('shop').collection('orders')

const changeStream = collection.watch()

changeStream.on('change', (event) => {
  console.log('Operation:', event.operationType)  // insert | update | delete
  console.log('Document key:', event.documentKey)

  if (event.operationType === 'insert') {
    console.log('New order:', event.fullDocument)
  }

  if (event.operationType === 'update') {
    console.log('Updated fields:', event.updateDescription.updatedFields)
  }
})

// Watch with a pipeline filter — only listen for inserts
const insertStream = collection.watch([
  { $match: { operationType: "insert" } }
])

// Resumable stream — store resume token and restart later
let resumeToken
changeStream.on('change', (event) => {
  resumeToken = event._id   // save this to persistent storage
  processEvent(event)
})

// Resume from where we left off
const resumedStream = collection.watch([], { resumeAfter: resumeToken })