How to create a strict Schema?

By default, it seems that when I create a schema, it’s flexible. Someone can add a new field as follows:

anythingHere: "anything here".

if I wanted to make a collection 100% strict, where people cannot add anything new, how do I lock it down?

Note - I am working from the Mongosh shell.

Hello @Kevin_Izevbigie, you can create a “strict schema” using the Schema Validation:

Apologies, I didn’t explain this well.

I have created a schema validation but I do not know how to prevent someone from adding new stuff?

Here is an example:

@Kevin_Izevbigie, you can try this approach, for example:

var schema =  {
      required: [ "name", "_id" ],
      properties: {
            _id: { bsonType: "objectId" },
            name: { bsonType: "string" }
      additionalProperties: false    // <------ this is the keyword to be used 

db.createCollection( "strict_coll", { validator: { $jsonSchema: schema } } )

Note that you have to specify the _id field also in the schema definition. Additional reference: $jsonSchema - Available Keywords


I see, so if additional properties are false, mongo will not automatically create an object id?

MongoDB will create the _id or you can supply one - as it is a mandatory field in a document.