Steps to create a simple schema with $jsonSchema

For example if I want to create a collection in the Mongodb shell named “contacts” that will store my data like this:

db.createCollection( “contacts”, {
validator: { $jsonSchema: {
bsonType: “object”,
required: [ “phone” ],
properties: {
phone: {
bsonType: “string”,
description: “anything”
},
email: {
bsonType : “string”,
pattern : “@example.com”,
description: “anything two”
}
}
}
)

is it strictly mandatory the part …“validator{:$jsonSchema:{”… ?. What if I omit it? will it still work out?. is it all we need in order to create a simple schema?.

What does mean the field : required: [ “phone” ] ?.

Thanks a lot

It is always best to look at the documentation when unsure. See https://docs.mongodb.com/manual/reference/method/db.createCollection/ for specific information on createCollection.

1 Like