Changing Validator properties of existing collection

14 views
Skip to first unread message

Chandraneel

unread,
Apr 24, 2018, 5:12:58 PM4/24/18
to mongodb-user
If suppose there already is a collection originally created using:

db.createCollection(
"employee",
  {
    validator: {
          $jsonSchema: {
                bsonType: "object",
                required: ["emp_id","emp_name"],
                properties: {
                     emp_id:{
                         bsonType: "string",
                         description: "Employee ID"  
                      },
                      emp_name:{
                         bsonType: "string",
                         description: "Employee Name"  
                      }                   
                    }               
              }
        },
    validationAction: "error"
  }
);

Now if suppose, I want to add new property like employee_contact (string) and remove emp_name from required. How can we achieve this?

Stephen Steneker

unread,
Apr 24, 2018, 6:57:30 PM4/24/18
to mongodb-user
On Wednesday, 25 April 2018 07:12:58 UTC+10, Chandraneel wrote:
Now if suppose, I want to add new property like employee_contact (string) and remove emp_name from required. How can we achieve this?

Hi Chandraneel,

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

Chandraneel

unread,
Apr 25, 2018, 7:20:03 AM4/25/18
to mongodb-user
Hi Stephen,
Thanks for the solution. And special thanks for the query to find documents that conforms the validation.
Reply all
Reply to author
Forward
0 new messages