• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing MongoDB  Schema

MongoDB Schema is not strictly enforced as in traditional relational databases. However, we can define a logical structure or schema for the documents to provide consistency and organization. The article will provide a way to create a schema-like structure in MongoDB. 

Advertisements

1. Define Schema for the collection of MongoDB

We can define our schema using schema validation for the specific collection and then insert documents that adhere to that schema. By defining a schema and enabling schema validation, we ensure that the documents inserted into the collection adhere to the defined structure and data types.

Here is a step-by-step instruction for creating a schema and inserting documents by it.


# Create Collection
db.createCollection("student", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: [ "name", "age", "course", "date" ],
      properties: {
        name: {
        bsonType: "string"
      },
      age: {
        bsonType: "int",
        minimum: 0
      },
      courses: {
        bsonType: "array",
        items: {
          bsonType: "string"
        }
      },
      date: {
        bsonType: "date"
       }
        
      }
    }
  }
})     
Schema in MongoDB

In this example, we first enable schema validation for a collection using the validator option and provide the schema definition using JSON Schema structure. Within the $jsonSchema, we set the schema rules for the new collection.

The schema specifies that each document in the collection should be an object and have required fields for name, age, courses, and  date required fields. Here, the name should be a string field, and the age should be an integer field. Then, we have a courses field which must be an array field where each item in the array must be a string. Lastly, we have specified the date field in the schema that must contain the date object.

2. Insert the Document into the Defined Schema

Once the schema has been established, we can insert following documents. MongoDB will check the inserted documents for compliance with the schema requirements. The example of inserting a document according to the defined schema is as follows.


# Inserting a document
db.student.insertOne({
  name: "Katherine James",
  age: 27,
  course: ["MongoDB", "Python", "SQL"],
  date: ISODate("2023-05-26T13:30:05Z")
})

In the example, we inserted the document into the student collection which includes the name field, age field, and course field that is specified with the string array items. Lastly, the date field with the ISO date format.

The document is inserted successfully into the collection since it satisfies the aforementioned schema.

Schema in MongoDB

However, if we attempt to insert a document that violates the schema, MongoDB will reject the operation. For instance, we tried to insert a document without the required fields as below.


# Inserting a document without the required fields
db.student.insertOne({
   name: "Kylie Joe"
})

In this example, we have just provided the name field for the collection that conforms to the schema defined for the student collection. As a result, the insertion failed because the other required fields were missing, and those fields are required according to the schema.

Schema in MongoDB

3. Analyze the Schema of the collection in MongoDB Compass

Additionally, we can explore the structure and data types existing in the MongoDB collection by using the analyze schema feature in MongoDB Compass. We provide the step to validate the schema of the collection student we created in the above section.

Firstly, we can see the document of the collection student, which we have inserted according to the defined schema.  Next to the Documents option on the top, we can visualize many other options. Among those options, our concern is with the schema option.

Schema in MongoDB

Inside the schema page, there is an Analyze Schema button. We need to click that to visualize the defined schema for the student collection.

Schema in MongoDB

Here, it displays an overview of the schema, including the field names, data types, and occurrence frequency. Moreover, we can expand the field names to view additional details. MongoDB Compass provides information such as the field’s data type, occurrence percentage, and a sample of the field’s values.

Schema in MongoDB

Moreover, we can visualize the validated schema for the student collection and update the defined schema if required by selecting the validation option.

Schema in MongoDB

4. Conclusion

In conclusion, we have defined and enabled the schema here for the document of the particular MongoDB collection. Although, insert the document in the collection that adheres to that schema. Lastly, analyze the schema of a MongoDB collection using the MongoDB Compass.

More details about this topic can be found here.