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'
  }
  OR
  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.

db.createCollection("contacts")

db.runCommand({
   collMod: "contacts",
   validator: { 
      $or: [ 
           {"phone": { $type: "string"}}, 
           {"email": { $type: "string"}}
       ]
    }
})

db.contacts.insertOne({ phone: "1234567890" })
db.contacts.insertOne({ email: "abc@xyz.com" })
db.contacts.insertOne({ phone: "1234567890", email: "abc@xyz.com" })
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.

2 Likes