Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Documents in a MongoDB collection have three historical shapes of the address field. Describe the schema versioning pattern and how you would migrate without downtime.

The schema versioning pattern adds a schemaVersion field to every document, so the application can recognise each of the three address shapes and map them to one model. Documents are upgraded to the latest shape whenever the application writes them, which is lazy migration, while a throttled background job converts the remaining old documents in batches. When no old versions remain, we remove the old read paths and tighten the validator, with tests that keep samples of every version.

Why this question is asked

Collections that have lived for years almost always contain several shapes of the same data. An address may once have been a single string, then an object with street and city, then an object with a lines array and a country code. Stopping the application to rewrite millions of documents is rarely acceptable. Interviewers ask about schema versioning to see whether we can change data shapes while the system keeps running. In this answer, we will recap the problem, introduce the schemaVersion field, write a reader that handles every shape, walk through lazy and background migration, and finish by retiring the old shapes.

1A Quick Recap of the Problem

MongoDB does not force every document in a collection to look the same. That is convenient when a model changes, because new code can write a new shape immediately. The cost is that old documents keep their old shape until someone rewrites them, so every reader must cope with all the shapes that exist.

Here are the three historical shapes of address in our example. The challenge is telling them apart reliably and converting them without downtime.

Java
// version 1 (2016): one string
{ _id: 1, name: "Ana", address: "12 Rua Azul, Lisbon" }
// version 2 (2019): an object
{ _id: 2, name: "Ben", address: { street: "5 Oak St", city: "Leeds", zip: "LS1 4AB" } }
// version 3 (2024): lines plus an ISO country code
{ _id: 3, name: "Chloe", schemaVersion: 3,
address: { lines: ["Flat 2", "9 Elm Rd"], city: "Austin", postalCode: "78701", country: "US" } }

2Adding a schemaVersion Field

The core of the pattern is one field that says which shape a document has. We could guess the shape from the data, for example a string means version 1, but guessing gets fragile as shapes multiply. An explicit schemaVersion makes the reader's job a simple switch and makes migration progress easy to measure.

Documents written before the field existed have no schemaVersion. We treat a missing value as the oldest version we cannot otherwise tell apart, and a one-off cheap update can label versions 1 and 2 using the type of address.

Java
// Label the old documents once (cheap: only sets a number)
db.customers.updateMany({ schemaVersion: { $exists: false }, address: { $type: "string" } },
{ $set: { schemaVersion: 1 } })
db.customers.updateMany({ schemaVersion: { $exists: false }, address: { $type: "object" } },
{ $set: { schemaVersion: 2 } })
db.customers.aggregate([{ $group: { _id: "$schemaVersion", n: { $sum: 1 } } }])
// { _id: 1, n: 1200000 } { _id: 2, n: 3400000 } { _id: 3, n: 900000 }

3Reading Every Version in the Application

The application keeps one model, the latest shape, and converts every older document into it when reading. In Spring Data MongoDB we can do that with a custom reading converter, or more simply by reading the raw Document in a small mapper class that the repository layer uses.

Java
record Address(List<String> lines, String city, String postalCode, String country) {}
class AddressReader {
Address read(Document doc) {
int v = doc.getInteger("schemaVersion", 1);
return switch (v) {
case 1 -> fromString(doc.getString("address")); // parse "12 Rua Azul, Lisbon"
case 2 -> { Document a = doc.get("address", Document.class);
yield new Address(List.of(a.getString("street")), a.getString("city"),
a.getString("zip"), null); } // country unknown in v2
case 3 -> fromV3(doc.get("address", Document.class));
default -> throw new IllegalStateException("unknown schemaVersion " + v);
};
}
}

Notice two details. Version 2 has no country, so the mapper leaves it null and the rest of the code must accept that until the data is enriched. And an unknown version fails loudly instead of guessing, which protects us if a newer service version writes a version 4 that this code has never seen.

4Lazy Migration on Write

Whenever the application saves a customer, it writes the latest shape with schemaVersion 3. Because every read converts to the latest model, saving that model back naturally upgrades the document. Active customers, the ones that matter most, are migrated within days without any special job.

But there is a catch: during a rolling deploy, old application instances may still be running and cannot read version 3. So we deploy the code that can read version 3 everywhere first, and only then enable writing it. Readers first, writers second is the rule that keeps a mixed fleet working.

Step throughA request touches an old document
ServiceAddressReaderMongoDB
find customer 2
schemaVersion 2, address object
read(document)
Address in the latest shape
change the phone number
save with schemaVersion 3

6 messages in order. Play them, or step through them one at a time.

The document is upgraded as a side effect of a normal write.

5The Background Job for the Rest

Lazy migration never reaches customers who do not come back. A background job finds old documents and upgrades them in small batches. It reads a batch of, say, 500 documents with schemaVersion below 3, converts each with the same mapper the application uses, and writes it back with a filter that includes the old version, so a document the application upgraded in the meantime is left alone. Then it sleeps briefly and continues.

Java
while (true) {
List<Document> batch = mongo.find(lt("schemaVersion", 3)).limit(500).into(new ArrayList<>());
if (batch.isEmpty()) break;
for (Document d : batch) {
Document upgraded = toV3(d);
mongo.replaceOne(and(eq("_id", d.get("_id")), eq("schemaVersion", d.getInteger("schemaVersion"))),
upgraded); // skipped if the app already upgraded it
}
Thread.sleep(200); // throttle: protect replication lag and latency
}

The throttle matters. Rewriting millions of documents generates a lot of oplog traffic, the log replica sets use to copy writes to secondaries. We watch replication lag and the latency of normal traffic, and slow the job down when either rises. An index on schemaVersion keeps the batch query cheap.

6Retiring the Old Shapes

When the count of documents below version 3 reaches zero and stays there, we remove the version 1 and 2 branches from the reader, keeping the failure for unknown versions. Then we tighten the collection validator so that address must have the version 3 shape and schemaVersion must be 3, which prevents an old script from writing a legacy shape again.

Throughout, the mapper is covered by tests that load real anonymised samples of every version and assert the resulting Address. These samples are the most valuable part of the safety net, because the edge cases live in old data: addresses with commas in the street, empty strings, missing cities.

7Follow-up questions

Why not migrate everything in one big script during a maintenance window?

For millions of documents, a single script can run for hours, hurt production latency and is hard to resume if it fails halfway. It also needs the application to stop writing or to coordinate carefully. Lazy migration plus a throttled, resumable background job reaches the same end state without downtime.

Where should the conversion code live?

In one place that both the application and the background job use, such as a shared mapper class. If the job had its own conversion logic, the two could disagree and produce documents that look like version 3 but differ in details.

Do we always need a schemaVersion field?

Not for every change. Adding an optional field that old documents simply lack needs no version. A version field earns its place when the same field changes meaning or type, as with our address, so readers cannot safely tell the shapes apart by inspection.

8Conclusion

In this answer, we saw how the schema versioning pattern handles three shapes of the address field. A schemaVersion field labels each document, a single reader maps every version to the latest model, and writes upgrade documents lazily, with readers deployed before writers. A throttled, resumable background job migrates the remaining documents, and when none are left we remove the old read paths and tighten the validator, protected by tests with samples of every version.

What to say in the interviewAbout 80 seconds aloud

Open with

I would use the schema versioning pattern. Every document gets a schemaVersion field; for old documents without it, I label them once with a cheap update based on the type of the address field, string for version 1, object for version 2.

Then, if they want more

The application keeps one model, the newest shape, and a single mapper converts each known version into it on read, failing loudly on an unknown version. Then migration happens in two ways. Lazily: whenever the application saves a document, it writes the latest shape with schemaVersion 3, so active records upgrade themselves.

I deploy the reading code everywhere before enabling writes of the new version, so a rolling deploy never has an old instance meeting a shape it cannot read.

And in the background: a job reads batches of documents below version 3, converts them with the same mapper, and replaces each with a filter on the old version so it does not overwrite something the application upgraded meanwhile. It is throttled, watching replication lag and latency, and resumable.

When the count of old versions stays at zero, I remove the old branches, tighten the validator to require version 3, and keep tests with real samples of every version throughout.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Documents in a MongoDB collection have three historical shapes of the address field....": https://scrivio-interview-library.netlify.app/databases/mongodb/46d2fe2d11/