Validation rule

It´s posible to add a validation rule, that allows me to require one of two posibble fields?

Example of the validation I need:

  phone :{
       bsonType: 'string'
  email : {
      bsonType: 'string'

I need that the schema require at least one (phone or email).

Hello @Jorge_Tenorio, welcome to the MongoDB forum!

Yes, you can do something like in the following example, run from mongo shell.


   collMod: "contacts",
   validator: { 
      $or: [ 
           {"phone": { $type: "string"}}, 
           {"email": { $type: "string"}}

db.contacts.insertOne({ phone: "1234567890" })
db.contacts.insertOne({ email: "" })
db.contacts.insertOne({ phone: "1234567890", email: "" })
db.contacts.insertOne({ address: "abc xyz 123" })

Of the four insert statements, only the last one will fail the validation.

Note that you can also create validation rules from the MongoDB Compass GUI.