While inserting a document I want to check using mongodb document validation feature that all the keys present in the document are from a predefined set of keys. Assume only "a","b","c" are allowed keys and doc1 and doc2 defined below are 2 documents:
{
"a": "any_value",
"b":"any_other_value"
},
{
"a": "any_value",
"b": "any_other_value",
"d": "other_value"
}
In this case doc1 is a valid document and doc2 is invalid.
Also, how to do this validation if in above case one more condition is added that all the keys must be present?
Note: I want to know if this can be done by Document Validation feature present in MongoDB 3.2
This is possible now in Mongo 3.6 using JSON Schema validation, like so:
db.createCollection("myCollection", {
validator: {
$jsonSchema: {
bsonType: "object",
additionalProperties: false,
properties: {
_id: {
bsonType: 'objectId',
},
a: {
bsonType: "string",
},
b: {
bsonType: "string",
},
}
}
}
});
Couple notes that might be helpful:
_id when using additionalProperties: false, or every document will fail validation.additionalProperties: false on every bsonType: "object" entry, otherwise that nested object will allow any additional properties on it.Documentation links:
https://docs.mongodb.com/manual/core/schema-validation/ https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With