0Pricing
MongoDB Academy · Lesson

Change Event Document Structure

Learners will inspect the fields of a change event—operationType, fullDocument, updateDescription, ns, documentKey—and handle each operation type.

Anatomy of a Change Event Document

Every event delivered by a change stream is a change event document with a standard set of fields. The most important fields are operationType (what happened), ns (which namespace was affected), documentKey (the _id of the affected document), and operation-specific fields like fullDocument and updateDescription. Understanding this structure lets you write event handlers that correctly react to each type of operation.

The operationType Field

The operationType field identifies what kind of change occurred. Common values include: 'insert' (new document added), 'update' (document fields modified), 'replace' (entire document replaced), 'delete' (document removed), and 'invalidate' (the change stream has been invalidated, e.g., the collection was dropped). There are also 'drop', 'rename', and 'dropDatabase' for collection/database operations.

for await (const change of changeStream) {
  switch (change.operationType) {
    case 'insert':   handleInsert(change); break;
    case 'update':   handleUpdate(change); break;
    case 'replace':  handleReplace(change); break;
    case 'delete':   handleDelete(change); break;
    case 'invalidate':
      console.log('Change stream invalidated — collection may have been dropped');
      await changeStream.close();
      break;
    default:
      console.log('Other operation:', change.operationType);
  }
}

All lessons in this course

  1. Opening a Change Stream on a Collection
  2. Change Event Document Structure
  3. Filtering Events With an Aggregation Pipeline
  4. Resuming Change Streams After Interruption
← Back to MongoDB Academy