MongoDB Best Practices

Chapter 2 · Practice 5 of 5

Add a schema version field and migrate lazily or in batches

From Schema design

Why it matters

Flexible documents let old and new shapes live side by side, which is handy during a change and confusing a year later. Add a schemaVersion field so code can tell which shape it is reading.

Two ways to migrate:

  1. Lazily: code reads both shapes and writes the new one whenever it updates a document.
  2. In batches: a background job updates documents in small batches by _id range, so it does not overload the cluster.

Either way, finish the migration and remove the code for the old shape. A collection that is permanently half-migrated is a source of bugs.