Schema validation with $or

Hi,

I’m trying to understand that on this link : https://docs.mongodb.com/manual/core/schema-validation/

For this code below, if I understand well, with the operator $or: It means that if one of the field in the list is validate during insert or update, it will be correct ? Can you give me more explanation plase.

db.createCollection( "contacts",
   { validator: { $or:
      [
         { phone: { $type: "string" } },
         { email: { $regex: /@mongodb\.com$/ } },
         { status: { $in: [ "Unknown", "Incomplete" ] } }
      ]
   }
} )

Thank you.

“Any of the following is valid.”

Atlas Cluster0-shard-0 [primary] jwoehr> db.createCollection("contacts", { validator: { $or: [ { phone: { $type: "string" } }, { email: { $regex: /@mongodb\.com$/ } }, { status: { $in: ["Unknown", "Incomplete"] } }] } })
{ ok: 1 }
Atlas Cluster0-shard-0 [primary] jwoehr> db.contacts.insertOne({phone: '123-456-7890', email: "foo@mongodb.com", status: "Unknown"})
{
  acknowledged: true,
  insertedId: ObjectId("610768cde0c8e93674082951")
}
Atlas Cluster0-shard-0 [primary] jwoehr> db.contacts.find()
[
  {
    _id: ObjectId("610768cde0c8e93674082951"),
    phone: '123-456-7890',
    email: 'foo@mongodb.com',
    status: 'Unknown'
  }
]
1 Like

Thank you @Jack_Woehr, I understand.

Thank you @Jack_Woehr, I understand.
But, Create validator with $jsonSchema or with an operator like $or, $and; witch is better or recommended ?

$or - $and mean different things, they are Boolean operators.

2 Likes

It’s correct, i understand. Thank you.