# MongoDB 6.0, and the change stream that can show you the before

> Change streams have always told you a document changed and what it became. 6.0 can also tell you what it was, which removes a category of code I have written more than once.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2022-08-20
- Tags: MongoDB, Databases, Node.js, Automation
- URL: https://deyanpeev.com/posts/the-change-stream-that-shows-the-before

MongoDB 6.0 shipped in July. The headline feature was Queryable Encryption,
available in preview, which lets a server run equality queries against data it
can't read. That's novel and I have no use for it today. So this post is about
a smaller thing in the release that I do have a use for. Change streams can now
hand you the document as it was before the change.

# What a change stream would and would not tell you

A change stream is a tailable view of the oplog with a sensible API on top. You
watch a collection and receive events as documents are inserted, updated,
replaced or deleted.

```js
const stream = db.collection('members').watch()

for await (const event of stream) {
  console.log(event.operationType, event.documentKey)
}
```

For an update, the event carries `updateDescription` (the fields that were set
and the fields that were removed) and, if you ask for it, `fullDocument`, the
document as it now stands.

What it never carried was the document as it stood a moment earlier, and a lot
of what people want to do with a change stream needs that.

Auditing needs it, because "who changed what" isn't much use without the
previous value. Any integration that fires on a transition needs it too. Send
the welcome email when a membership becomes active, and you have to know it
wasn't active before, or the first unrelated update to an active member sends it
again. Same for anything feeding a downstream system that wants
before-and-after rows.

The workarounds are all bad. You keep a copy of every document in the consumer
so you can diff against it, and now you have a second store that can drift and a
cold-start problem. Or you reconstruct the previous state by inverting
`updateDescription` against `fullDocument`, which works until an update touches
an array or a nested path. Or you write the previous values into the document
itself and every schema becomes an audit schema.

I've written the first and the second. I wasn't proud of either.

# What 6.0 added

Pre-images and post-images, enabled per collection:

```js
db.createCollection('members', { changeStreamPreAndPostImages: { enabled: true } })
// or on an existing one
db.runCommand({ collMod: 'members', changeStreamPreAndPostImages: { enabled: true } })
```

Then ask for them when you open the stream:

```js
const stream = db.collection('members').watch([], {
  fullDocument: 'whenAvailable',
  fullDocumentBeforeChange: 'whenAvailable',
})

for await (const event of stream) {
  const before = event.fullDocumentBeforeChange
  const after = event.fullDocument

  if (before?.status !== 'active' && after?.status === 'active') {
    await onActivated(after)
  }
}
```

That conditional is the transition, written in one place, and the consumer
doesn't have to remember anything between events. It is stateless now, so it can
be restarted, scaled out or replaced without a warm-up.

# When the pre-image is missing

`whenAvailable` matters in that snippet, and I wouldn't swap it for `required`
without thinking.

Pre-images are stored, so they take space and they expire. If the image for an
event has been removed before your consumer gets to it (because the consumer
was down longer than the retention window) then `required` makes the stream
error, and `whenAvailable` gives you an event with the field missing. Both are
legitimate, they just push the decision to different places. What you must not
do is write `before?.status !== 'active'` and let a missing image count as "it
was not active". The optional chaining above will do that if you're not paying
attention. For anything where a duplicate action is expensive, the missing-image
case needs its own branch.

It's also opt-in per collection and it is not retroactive. Turning it on today
doesn't give you pre-images for yesterday.

# Why I think this is the interesting one

Queryable Encryption is the more impressive engineering by a distance, but this
is the feature that deletes code.

The pattern it removes is a consumer keeping its own shadow copy of state purely
to detect transitions. It's one of those designs that looks reasonable when you
write it and slowly becomes a liability. It has a cold start, it drifts, and it
has to be reasoned about during every incident because it's never clear whether
its copy is current. And it only exists because the event was missing one field
that the database already had.

The rest of the release is the usual. Time series collections got faster and
learned more index types, and the aggregation pipeline picked up operators that
mean fewer round trips. Useful, but pre-images are what changed a design I would
otherwise have written again.
