Add new Validator to Existing Collection

Viewed 8656

I'm trying to add new field (LastLoginDate of type Date) to a existing collection. Here is my sample script:

db.createCollection( "MyTestCollection",
   { "validator": { "$or":
       [
          { "username": { "$type": "string" } },
          { "notes": { "$type": "string" } }
       ]
    }
   }
)

db.getCollectionInfos({name: "MyTestCollection"});
  [
     {
        "name" : "MyTestCollection",
        "options" : {
           "validator" : {
              "$or" : [
                 {
                    "username" : {
                       "$type" : "string"
                    }
                 },
                 {
                    "notes" : {
                       "$type" : "string"
                    }
                 }
              ]
           }
        }
     }
  ]

What is the best way to add new field LastLoginDate : { $type: "date" }, to this existing collection "MyTestCollection".

Adding new document or updating existing collection with new field may create this field. But i'm not sure how to enforce the date type on the new field. After adding new filed, if i execute the following command again, it doesn't show type validator for newly added field.

2 Answers
let previousValidator = db.getCollectionInfos({name: "collectionName"})[0].options.validator;
# push the key to required array
previousValidator.$jsonSchema.required.push("isBloodReportAvailable")

let isBloodReportAvailabl = {"bsonType" : "bool", "description" : "must be an bool object and is optional" }
# add new property to validator
previousValidator1.$jsonSchema.properties['isBloodReportAvailable'] = isBloodReportAvailabl

db.runCommand({
  "collMod": "collectionName",
  "validator": previousValidator,
});
Related