validator
open fun validator(level: ValidationLevel = ValidationLevel.Strict, action: ValidationAction = ValidationAction.Error, validator: FilterQuery<Document>.() -> Unit)(source)
Specifies validation rules for a collection.
By default, MongoDB accepts any document even if it doesn't look like other documents in the same collection.
By declaring validation rules, MongoDB will reject inserts and updates that do not pass these rules, which can help ensure the collection isn't corrupted.
Example
For example, if we want to ensure all birth dates as stored as MongoDB's native BsonType.Datetime and never as a BsonType.String.
class User(
val name: String,
val age: Int,
val birthdate: Instant,
)
users.create {
validator {
User::birthdate hasType BsonType.Datetime
}
}Content copied to clipboard
If we try to insert a document with a string birthdate, for example in an external migration script, MongoDB will reject it.
See also
How strict is MongoDB with the configured validator.
How MongoDB reacts when validation fails.
Allow a write operation to ignore the configured validator.