← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 7 of 7

Schema versioning

A schemaVersion field lets old and new document shapes coexist while you migrate gradually.

In this page:

  1. Schema versioning

Schema versioning

Store schemaVersion in each document. Application code reads and handles every version it may encounter, and a background job upgrades old documents to the newest shape. This avoids downtime and big-bang migrations in a schemaless database.

Note: Upgrade lazily on read or in batches with updateMany.

Example: Schema versioning

bash
test> db.users.insertMany([{ _id: 1, schemaVersion: 1, name: "Ada Lovelace" }, { _id: 2, schemaVersion: 2, firstName: "Alan", lastName: "Turing" }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.users.find({ schemaVersion: 1 }).forEach((u) => db.users.updateOne({ _id: u._id }, { $set: { schemaVersion: 2, firstName: u.name.split(" ")[0], lastName: u.name.split(" ")[1] }, $unset: { name: "" } }))
test> db.users.find()
[
  {
    _id: 1,
    schemaVersion: 2,
    firstName: 'Ada',
    lastName: 'Lovelace'
  },
  {
    _id: 2,
    schemaVersion: 2,
    firstName: 'Alan',
    lastName: 'Turing'
  }
]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Changing document shape without a version marker
  2. Breaking readers of older versions
  3. Migrating everything in one long lock
Chapter Summary
  • Add schemaVersion to documents
  • Code handles multiple versions
  • Migrate gradually
  • Batch updates upgrade old data

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.