Scrivio Interview library
LeadershipPrincipal6 min read · updated 12 November 2026

Your company built its main product on MongoDB ten years ago with no schema enforcement, and now has documents in many historical shapes. What long-term plan would you set?

I would first inventory the document shapes and the code that reads each one, and put a number on what handling every variant costs us. Then I would stop the problem growing by adding schema validation for new writes, bring old documents to the current shape with a version field, either lazily when they are read or in batch jobs, and decide honestly whether some of the data belongs in a relational store. The lasting lesson to record is that schema-less storage still has a schema; it is only enforced in code, by everyone, forever.

Why this question is asked

Ten years of writes without enforcement leaves a collection that looks like geology: documents from 2016 with an address as a string, from 2019 with an address object, from 2022 with a list of addresses, and a few with typos in field names that one old release produced. Every new feature has to handle all of them, and every bug fix risks breaking one of them. Interviewers ask this leadership question to see whether we can plan a long migration that the business can afford, rather than proposing a big-bang rewrite. In this answer, we will see how to measure the problem, freeze it with validation, migrate with version fields, decide what should move to a relational store, and capture the lesson for the organisation.

1A Quick Recap: Why Shapes Multiply

MongoDB does not require documents in a collection to share fields or types. That flexibility is what let the product move fast early on: a new field could be added in code without a migration. The cost is that old documents keep their old shape forever unless someone changes them. Each release that changed the model added another shape, and the code that reads documents accumulated branches such as if address is a string, parse it; if it is an object, use it; if it is a list, take the first.

So the real schema lives in the reading code, spread across services, and nobody can see it in one place. That is the problem we are actually solving.

2Inventory the Shapes and Their Consumers

We cannot plan without data, so we measure. An aggregation over each collection, or over a sample of it on very large collections, groups documents by the presence and type of their fields, which tells us how many shapes exist and how common each is.

Java
db.customers.aggregate([
{ $sample: { size: 200000 } },
{ $group: { _id: { address: { $type: "$address" }, v: { $ifNull: ["$schemaVersion", 0] } },
n: { $sum: 1 } } },
{ $sort: { n: -1 } }
])
// { _id: { address: "object", v: 0 }, n: 151230 }
// { _id: { address: "string", v: 0 }, n: 41002 }
// { _id: { address: "array", v: 0 }, n: 7650 }
// { _id: { address: "missing", v: 0 }, n: 118 }

Alongside the shapes, we list the consumers: services, reports, exports and data pipelines that read each collection, found through code search, database profiling and connection logs. Then we quantify the cost of the variants: incidents caused by unexpected shapes in the last year, time spent on branches in reading code, and features delayed by them. A sentence such as "four of our last eleven customer incidents came from legacy address shapes" is what gets a migration funded.

3Stop New Variants With Schema Validation

Before cleaning the past, we stop adding to it. MongoDB supports validation rules on a collection using $jsonSchema, a JSON Schema description of the allowed shape. With validationLevel moderate, the rules apply to inserts and to updates of documents that already pass validation, while existing invalid documents can still be updated, so legacy data does not break the running system.

Java
db.runCommand({
collMod: "customers",
validator: { $jsonSchema: {
bsonType: "object",
required: ["email", "schemaVersion"],
properties: {
schemaVersion: { bsonType: "int", minimum: 3 },
addresses: { bsonType: "array", maxItems: 20 }
} } },
validationLevel: "moderate",
validationAction: "warn" // log violations first; switch to "error" once writers are fixed
})

Starting with validationAction warn means violations are only logged, so we can find every writer that still produces an old shape before we switch to error and reject them. This is how we introduce enforcement without an outage.

4Migrate Old Documents With a Version Field

Every document gets a schemaVersion field. Code that reads documents runs them through a chain of upgrade functions, version 0 to 1, 1 to 2 and so on, so the rest of the code sees only the current shape. This is the single place where knowledge of old shapes lives, instead of branches everywhere.

Then we migrate in two ways. Lazily on read: when a service loads an old document, it upgrades it and writes back the current version, so frequently used data migrates itself. In batch jobs: a background job walks the collection in small id ranges, upgrades documents with bulk writes, throttles itself to protect production latency, and records progress so it can resume. Lazy migration alone never finishes, because documents nobody reads stay old forever, so the batch job is what lets us eventually delete the upgrade chain.

Step throughReading a customer during the migration
  1. Load document
  2. schemaVersion is current?
    YesReturn itNoRun upgrade chain v0 -> v1 -> v2 -> v3
  3. Write back with schemaVersion 3conditional on the old version, so a racing writer is not overwritten
  4. Return the current shaperest of the code sees one shape

4 steps in order. Play them, or step through them one at a time.

A batch job does the same for documents nobody reads, so the chain can be deleted later.

5Decide What Belongs in a Relational Store

The inventory often shows that parts of the data have become deeply relational: billing records referenced from five collections, reports joining customers with orders in application code, or invariants such as unique emails enforced by hope. For those parts, moving to PostgreSQL, with its constraints, transactions and joins, may cost less over the next ten years than continuing to enforce structure by hand. Other parts, such as product content or user preferences, genuinely benefit from flexible documents and can stay.

This is a decision per bounded area, not a verdict on MongoDB. We estimate the migration cost, the risk, and the yearly cost of staying, and we move the parts where staying costs more. A move uses the same tools as any migration: change data capture or dual reads, a backfill, and verification by comparing counts and checksums.

6Record the Lesson

The most valuable outcome is cultural. Schema-less storage still has a schema; the only question is where it is enforced. Without validation it is enforced in every reader, by every developer, forever, and nobody sees the whole picture. So the organisation adopts a few lasting rules: every collection has a validator, every document has a version, every model change ships with its upgrade step, and new services describe their document shapes in the repository like any other contract. We write this down in an architecture decision record so the next team does not repeat the experiment.

7Follow-up questions

How long would such a plan take?

Inventory and validation in warn mode take weeks. Turning validation to error depends on fixing writers, usually one or two quarters. The batch migration of old documents can run in the background over months. Moving parts to a relational store is a separate, larger project per area, planned only where the numbers justify it.

Why not migrate everything in one big job over a weekend?

Because with many consumers we cannot be sure every reader handles the new shape on the same day, a long job on a large collection hurts production, and a mistake affects all data at once. Gradual migration behind an upgrade chain lets readers and data move independently and lets us stop safely.

How do you know when the migration is finished?

When the shape inventory shows zero documents below the current version, validation is in error mode, and no reader logs an upgrade for a period such as a month. Then the upgrade chain and the validator's legacy allowances can be deleted.

8Conclusion

In this answer, we turned a decade of uncontrolled document shapes into a plan. We measured the shapes and their consumers and put a cost on them, stopped new variants with $jsonSchema validation introduced in warn mode, migrated old documents through a version field and an upgrade chain both lazily and in throttled batch jobs, and decided per area whether relational storage would serve better. The lesson we record is that schema-less data still has a schema, so we choose to enforce it where everyone can see it.

What to say in the interviewAbout 90 seconds aloud

Open with

I would not start with a rewrite; I would start by measuring. I would run aggregations that group documents by which fields exist and their types, so I know how many shapes there are and how common each is, and I would list every consumer: services, reports, pipelines.

Then, if they want more

Then I put a cost on it, like how many incidents in the last year came from unexpected shapes. That number is what gets the work funded.

Next, stop the bleeding: add $jsonSchema validation to each collection with validation level moderate, so existing documents are not blocked, and action warn first, so we find the writers still producing old shapes before switching to error. Then migrate. Every document gets a schemaVersion, and reading code passes documents through one upgrade chain, so old-shape knowledge lives in one place.

Documents are upgraded lazily when read and written back, and a throttled, resumable batch job handles the ones nobody reads, because lazy migration alone never finishes. In parallel, I would look at which parts have become relational, like billing or anything needing uniqueness and joins, and move those to PostgreSQL where staying costs more than moving.

And I would write down the lesson: schema-less storage still has a schema, it is just enforced in code by everyone forever, so every collection gets a validator and every model change ships with its upgrade step.

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
Spring Data reference
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 "Your company built its main product on MongoDB ten years ago with no schema enforcement...": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/9107f69e9e/