Now if suppose, I want to add new property like employee_contact (string) and remove emp_name from required. How can we achieve this?
You can use the collMod
command to update the validator for an existing collection.
Example of your updates using the mongo
shell:
// Retrieve the current validator
var schema = db.getCollectionInfos({name:"employee"})[0].options.validator
// Update required fields
schema["$jsonSchema"].required = ["emp_id"]
// Add employee_contact rule
schema["$jsonSchema"].properties.employee_contact = {
bsonType: "string",
description: "Employee Contact"
}
// Update the validator
db.runCommand({collMod:'employee', validator: schema})
You may also want to check if existing documents will match a schema using the $jsonSchema
query operator. The operator uses the same format as the $jsonSchema
validator so the example from above can be used directly:
// Find documents not matching the schema
db.employee.find({$nor: [ schema ]})
// Find documents matching schema
db.employee.find(schema)
Regards,Stennie