Schema versioning
A schemaVersion field lets old and new document shapes coexist while you migrate gradually.
In this page:
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
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
- Changing document shape without a version marker
- Breaking readers of older versions
- Migrating everything in one long lock
Chapter Summary
- Add schemaVersion to documents
- Code handles multiple versions
- Migrate gradually
- Batch updates upgrade old data
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: