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

Schema का Versioning

एक schemaVersion field old और new document shapes को coexist करने देता है जबकि आप gradually migrate करते हैं।

In this page:

  1. Schema Versioning

Schema Versioning

हर document में schemaVersion store करें। Application code हर version पढ़ता और handle करता है जो यह encounter कर सकता है, और एक background job old documents को newest shape में upgrade करता है। यह एक schemaless database में downtime और big-bang migrations से बचाता है।

Note: read पर lazily upgrade करें या updateMany से batches में।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक version marker के बिना document shape बदलना
  2. older versions के readers तोड़ना
  3. एक लंबे lock में सब कुछ migrate करना
चैप्टर सारांश
  • Documents में schemaVersion add करें
  • Code कई versions handle करता है
  • Gradually migrate करें
  • Batch updates old data upgrade करते हैं

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.