Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Add schema validation to an existing MongoDB users collection so email must be a string and age, if present, an integer of at least 0, without breaking writes to existing invalid documents.

We run collMod on the users collection with a $jsonSchema validator that requires email as a string and allows age only as an int of at least 0, and we set validationLevel to moderate. Moderate applies the rules to every insert and to updates of documents that already pass, so the old invalid documents can still be updated. We can start with validationAction warn, find the invalid documents with $nor and the same schema, fix them, and then move to strict and error.

Why this question is asked

Adding validation to a collection that has been written by several versions of an application for years is a delicate change. If we switch on strict rules in one step, the next update to an old, slightly wrong document fails, and that shows up as errors in production code that did nothing wrong. Interviewers ask this to see whether we know MongoDB's validation options well enough to tighten the rules gradually. In this answer, we will recap how validators work, write the command, see exactly what moderate does, find and fix the invalid documents, and then make the rules strict.

1A Quick Recap of MongoDB Validators

A MongoDB collection can carry a validator: a rule that every write is checked against. The usual way to write it is $jsonSchema, a subset of JSON Schema with MongoDB's own bsonType keyword for the BSON types: string, int, long, double, date, object, array and so on.

Two settings decide how the rule is applied. validationLevel says which writes are checked: strict, the default, checks every insert and update; moderate checks inserts and updates to documents that already pass; off checks nothing. validationAction says what happens when a write fails the rule: error, the default, rejects it; warn accepts it and writes a warning to the server log.

2Writing the collMod Command

collMod changes the options of an existing collection without rebuilding it. Here is the command for our rules.

YAML
db.runCommand({
collMod: "users",
validator: { $jsonSchema: {
bsonType: "object",
required: ["email"],
properties: {
email: { bsonType: "string" },
age: { bsonType: "int", minimum: 0 }
}
} },
validationLevel: "moderate",
validationAction: "error"
})
// { ok: 1 }

Notice how the rules express the question. email is in required, so it must exist, and must be a string. age is listed under properties but not under required, so a document without age passes, while a document with age must hold an int of 0 or more. Adding the validator does not scan existing data, so it returns at once even on a large collection.

But there is a catch with int. In the mongo shell, a plain number such as 30 is stored as a double, not an int, unless we write NumberInt(30). Java drivers store a Java int as int32 and a long as int64, so a Spring entity with Integer age is fine, but scripts that write ages from the shell would fail this rule. If we want to accept any integer type, we can use bsonType: ["int", "long"].

3What Moderate Does for Existing Documents

With validationLevel moderate, MongoDB checks the document as it would be after each write. For inserts, it always checks. For updates, it checks only if the existing document already satisfied the rules. An already invalid document can be updated freely, even if the result is still invalid, which is exactly what keeps old data from breaking today's code.

Java
db.users.insertOne({ email: "new@example.com", age: NumberInt(-1) })
// error: Document failed validation (inserts are always checked)
// An old document that was invalid before the validator existed:
// { _id: 7, email: 12345, name: "legacy" }
db.users.updateOne({ _id: 7 }, { $set: { name: "legacy user" } })
// { matchedCount: 1, modifiedCount: 1 } allowed, it was already invalid
// A valid document cannot be made invalid:
db.users.updateOne({ email: "ana@example.com" }, { $set: { age: "thirty" } })
// error: Document failed validation
Step throughHow a write is checked under moderate
  1. Is it an insert?
    YesCheck against the schemaNoIt is an update
  2. Was the existing document valid?
    YesCheck the result against the schemaNoAllow the update without checking
  3. Does the result pass?
    YesWrite itNoReject, or log a warning if action is warn

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

Old invalid documents keep working; new and valid ones are protected.

4Starting With warn

If we are not sure how much of today's traffic would fail the rules, we can begin with validationAction warn. Every write is then accepted, but each one that would fail is logged by the server with the reason. After a few days we read the log, find the code paths that write bad data, and fix them before switching to error. This turns a risky change into a safe trial period.

Java
db.runCommand({ collMod: "users", validationAction: "warn" })
// server log entry for a failing write includes the message
// "Document would fail validation" and the details of which rule failed

5Finding and Fixing the Invalid Documents

The validator only checks writes, so we still need to find the documents that are invalid today. $jsonSchema can also be used as a query operator, and wrapping it in $nor returns everything that does not match.

Java
const schema = { bsonType: "object", required: ["email"],
properties: { email: { bsonType: "string" }, age: { bsonType: "int", minimum: 0 } } };
db.users.countDocuments({ $nor: [ { $jsonSchema: schema } ] }) // 312
db.users.find({ $nor: [ { $jsonSchema: schema } ] }).limit(5) // inspect samples
// Example fix: ages stored as doubles from shell scripts
db.users.updateMany({ age: { $type: "double" } }, [ { $set: { age: { $toInt: "$age" } } } ])

Each kind of problem gets its own fix: converting types, moving emails stored under another field name, or flagging documents that need a person to decide. When the count reaches 0, we tighten the collection with validationLevel strict and validationAction error, so every write from then on must pass.

6Follow-up questions

Does adding a validator lock or rescan the collection?

No. collMod stores the new validator in the collection's options and applies it to later writes only. Existing documents are not checked, which is why the command returns quickly and why we must look for invalid documents ourselves with a $nor query.

How do I see why a write failed validation?

Since MongoDB 5.0, the error for a failed validation includes details that name the failing rule and field, for example which property had the wrong type. In Spring, the error arrives as a DataIntegrityViolationException or a related exception wrapping the server message, so log the full message when it happens.

Can I bypass validation for a one-off repair?

Yes, a user with the right privilege can pass bypassDocumentValidation: true on a write command. It is useful for a migration script that moves data through an intermediate state, but it should be rare and reviewed, because it defeats the purpose of the rules.

7Conclusion

In this answer, we added schema validation to an existing users collection with collMod and a $jsonSchema validator requiring a string email and an optional int age of at least 0. With validationLevel moderate, inserts and updates to valid documents are checked while existing invalid documents can still be updated. We can use validationAction warn as a trial, find invalid documents with $nor and the same schema, fix them, and then move to strict and error.

What to say in the interviewAbout 70 seconds aloud

Open with

I would use collMod with a $jsonSchema validator on the users collection: bsonType object, email in the required list with bsonType string, and age under properties with bsonType int and minimum 0, but not required, so it is only checked when present.

Then, if they want more

The key setting is validationLevel moderate. With moderate, MongoDB checks every insert, and checks updates only for documents that already pass the rules, so the old invalid documents can still be updated by today's code without errors, while valid documents can never be made invalid.

If I am unsure how much current traffic would fail, I would start with validationAction warn, which accepts the writes but logs each violation, and fix the code paths I find. collMod does not scan existing data, so next I find the invalid documents with a $nor query wrapping the same $jsonSchema, look at samples, and fix them by kind, for example converting doubles written from the shell to int, since the shell stores plain numbers as doubles.

When that query returns zero, I switch to validationLevel strict and validationAction error, so every write must pass from then on.

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 "Add schema validation to an existing MongoDB users collection so email must be a string...": https://scrivio-interview-library.netlify.app/databases/mongodb/f28a4c2640/