APPENDIX · P10 · MongoDB · SCHEMA · FOR SLIDES 4–5
← Back to Slide 5
P10. Schema Version and Lazy Migration
// Веб-база: v1 имеет nick:string и lvl:int
db.lab_profiles.find({}, { schema_version: 1 })
db.lab_profiles.updateOne({ _id: 1042, schema_version: 1,
nick: { $type: "string" }, lvl: { $type: "int" } },
[{ $set: { nickname: "$nick", level: "$lvl",
region: "unknown", schema_version: 2 } },
{ $unset: ["nick", "lvl"] }])
db.lab_profiles.findOne({ _id: 1042 })
db.lab_profiles.updateOne({ _id: 1042, schema_version: 1 },
[{ $set: { schema_version: 2 } }])
db.lab_profiles.countDocuments({ schema_version: { $lt: 2 } })
What the result should be
1042: v1, 2001: v1, 3003: v2
matchedCount: 1, modifiedCount: 1
{ _id: 1042, schema_version: 2,
nickname: 'Klinok', level: 13,
region: 'unknown' }
matchedCount: 0 // повтор не сработал
1 // осталась 2001 в v1
schema_version
Lazy Migration
Batch Migration
Document form number. The code reads all active versions until the older ones have been migrated.
In the code, migration occurs with an explicit `updateOne`. "Lazy" migration requires a call when reading or writing in the application.
Before `updateMany`: filter `version=1`, check `nick`/`lvl` and validity;
then the v2 audit, only after the validator.
A flexible schema consists of several document formats at the same time. Migrations don't disappear: they become gradual, and the code handles them.