In MongoDB 9.0, what does `validationLevel: "constraint"` guarantee beyond `strict`, what does it take away, and how do you move an existing collection onto it?
answer
- a claim about stored documents, not writes
- something scanned once, on the way in
- three things it stops allowing
- a flag set by an earlier collMod
- reachable only from strict
basics
~20 sMongoDB 9.0's constraint level guarantees every stored document satisfies the validator, because moving to it scans them all. It refuses bypassDocumentValidation, the warn action and validator changes. Move from strict: set prepareConstraintValidationLevel, then collMod to constraint.
solid answer
~50 s`strict` checks every insert and update but says nothing about documents already stored, so an old invalid document can sit there untouched. `validationLevel: "constraint"`, new in MongoDB 9.0, adds the guarantee: every document in the collection satisfies the validator, so a reader can rely on the rules. The price is three restrictions: `validationAction` must be `error` or `errorAndLog`, not `warn`; the validator cannot change while the level holds; and any write with `bypassDocumentValidation: true` is refused, even for a valid document. To move an existing collection, be at `strict`, run `collMod` with `prepareConstraintValidationLevel: true`, then a second `collMod` setting `validationLevel: "constraint"`, with no validator in it. That second step scans every document and fails if one violates, which can be expensive on a large collection. To change the rules later, drop to `strict`, change them, prepare again and rescan. A collection created at `constraint` needs no preparation.
code
javascript · 8 lines// orders is at strict, with its final validator and validationAction "error"
db.runCommand({ collMod: "orders", prepareConstraintValidationLevel: true })
// a separate collMod: scans every document, fails if one violates
db.runCommand({ collMod: "orders", validationLevel: "constraint" })
// the level now reads constraint and the prepare flag is gone
db.getCollectionInfos({ name: "orders" })[0].optionsgo deeper
Recall that constraint is a validationLevel new in MongoDB 9.0, and that it promises every stored document conforms, where strict only checks new writes.
Explain what it takes away: the warn action, bypassDocumentValidation and in-place validator changes. Say why moving to it needs a full scan when attaching a validator at strict does not.
Plan the move on a live collection: strict first, the bypassing script fixed, the prepare flag, then the scanning collMod. Say what a violating document leaves behind and how you recover.
Weigh the guarantee against its running cost: a full scan for every rule change, a window with no guarantee, and no escape hatch for restores. Decide which collections earn it, knowing 8.0 deployments cannot have it.
## What the level is A MongoDB collection validator is a rule, usually a `$jsonSchema`, that a write must satisfy. `validationLevel` decides which documents the rule applies to. **`constraint`**, new in MongoDB 9.0, makes a claim about the whole collection rather than about the next write: the manual states that every document in the collection satisfies the rules. A team on 8.0 has no such level, and its nearest answer to "do all documents conform?" is a query that counts the offenders. ## What it adds over `strict` `strict`, the default, checks every insert and update against the document the write would leave behind. It never looks back. A document stored before the rules existed, one written with `bypassDocumentValidation`, or one left behind when the rules changed stays in the collection until something updates it. So a collection at `strict` tells a reader nothing certain about any stored document. `constraint` closes those routes, and each one costs something: - **Stored documents.** Moving to the level scans every document, and the `collMod` fails if one violates the validator. - **Bypass.** A write with `bypassDocumentValidation: true` fails with `BadValue` even when the document is valid, because the refusal comes before the rules are evaluated. - **Rule changes.** `collMod` refuses a new `validator`, so the rules the scan proved remain the rules in force. - **Logged-only failures.** `validationAction` must be `error` or `errorAndLog`. `warn`, which applies a failing write and logs it, is refused. | | `strict` | `constraint` | |---|---|---| | Inserts and updates checked | Yes | Yes | | Stored documents checked when the level is set | No | Every one | | `validationAction` | `error`, `warn`, `errorAndLog` | `error`, `errorAndLog` | | Client `bypassDocumentValidation` | Allowed with the privilege | Refused | | `collMod` with a new `validator` | Allowed | Refused | Two limits on the word "guarantee". The refusal covers client writes: the server's internal operations, such as oplog application and initial sync, skip the check under their own flag. And the guarantee lasts only while the level does, because a privileged `collMod` can lower it. A job that depends on it can read `options.validationLevel` from `db.getCollectionInfos()`. ## Moving an existing collection Take an `orders` collection long at `strict`, a reporting job that wants to trust its shape, and a backfill script that passes `bypassDocumentValidation`. 1. **Settle the rules and the writers.** Put the final validator in place, set the action to `error` or `errorAndLog`, and take the bypass option out of the script. Counting offenders with `$nor` and `$jsonSchema` tells you whether the scan can pass. 2. **Be at `strict`.** `constraint` is reachable only from `strict`; from `moderate` the `collMod` is refused. 3. **Prepare.** Run `collMod` with `prepareConstraintValidationLevel: true`. From here bypass writes and validator changes are refused, while the level is still `strict`. 4. **Upgrade.** Run a second `collMod` with `validationLevel: "constraint"`. It cannot carry a `validator`, and it cannot be merged with step 3, because the upgrade checks that the flag is already stored. This is the command that scans. The manual warns the scan can be computationally expensive on a large collection, so schedule it like one. On success the flag is cleared. A collection created with `validationLevel: "constraint"` needs none of this, because it holds nothing to scan. ## What fails, and how you recover - **A document violates.** The `collMod` fails and the level stays `strict`. The flag stays set, so bypass and validator changes are still refused. Fix the document with an ordinary update and run the upgrade again, which scans again. - **The rules were wrong.** Send `prepareConstraintValidationLevel: false` first; only then will `collMod` accept a new validator. - **The action is `warn`.** The upgrade is refused with `BadValue` until the action is `error` or `errorAndLog`. - **A restore passes `--bypassDocumentValidation`.** The inserts from `mongorestore` fail on this collection like any other bypass write, so check the runbook before you need it. - **The collection is the wrong kind.** `collMod` refuses the prepare option on views and time-series collections. ## Changing the rules, and leaving At `constraint`, a rule change is a planned operation. Lower the level with `collMod` to `strict`, change the `validator`, set `prepareConstraintValidationLevel: true` again (the upgrade cleared it, and the next upgrade insists on it), then upgrade. That rescans the collection and fails if any document breaks the new rules. While the level is down, bypass works again and the guarantee is gone. The level is also gated by the feature compatibility version (FCV), as read at r9.0.4. A deployment upgraded from 8.0 whose FCV is still 8.0 rejects it as not supported. In the other direction, lowering the FCV fails with `CannotDowngrade` while any collection is at `constraint` or has the prepare flag set, so lower the level and clear the flag, or drop the collection, first. ## When it is worth it Use it where something downstream depends on the shape and no writer needs an escape hatch. Leave a collection at `strict` where the rules change often, since each change means a lowered level and another full scan, or where restores of older data must bypass validation.
- Why does MongoDB's move to `constraint` need a separate `prepareConstraintValidationLevel` step first?It closes the routes that could undo the scan. With the flag set, a bypass write fails and the validator cannot change; at `strict` with an `error` action, every ordinary write must already produce a valid document. So what the scan passes stays valid, against the rules it checked. The upgrade checks that the flag is already stored, so the two cannot share one `collMod`, and a successful upgrade clears it.
- A nightly backfill passes `bypassDocumentValidation: true` to a MongoDB collection at `constraint`. What happens, and what do you change?Each such write fails with `BadValue`, even when the document is valid, because the refusal comes before the rules run. The same happens from the moment the prepare flag is set. Remove the option so the writes pass validation normally. If the job truly has to store invalid documents, that collection cannot stay at `constraint`: it goes back to `strict` and gives up the guarantee.
- The MongoDB `collMod` to `constraint` fails because a document violates the validator. What state is the collection in?Still at `strict`, with the prepare flag still set, so bypass and validator changes remain refused. Fix the document with an ordinary update and run the `collMod` again, which scans again. If the rules are what was wrong, send `prepareConstraintValidationLevel: false` first, change the validator, then prepare and upgrade.
- How does MongoDB's `constraint` level affect lowering the feature compatibility version?At r9.0.4 the downgrade fails with `CannotDowngrade` while any collection is at `constraint` or has `prepareConstraintValidationLevel` set. Lower those collections to a supported level and clear the flag, or drop them, first. A collection with the `errorAndLog` action blocks the downgrade the same way when the target version lacks it.
- Says constraint is just strict with error, adding nothing about stored documents
- Believes moving an existing collection to constraint needs no scan
- Expects the restore or dbAdmin role to keep bypassDocumentValidation working at constraint
- Sends prepareConstraintValidationLevel and validationLevel constraint in one collMod
- Plans a warn observation window while the collection sits at constraint
- Edits the validator in place at constraint instead of lowering the level first
Assumes MongoDB 9.0; the constraint level and prepareConstraintValidationLevel were read at r9.0.4, and a team on 8.0 has neither, nor errorAndLog, which the manual dates to 8.1.