MongoDB

How to use $jsonSchema operator in MongoDB

MongoDB is a NoSQL type of database to manage data at large scale. The most salient feature that enabled MongoDB to gain heights is the flexible schema support as compared to SQL type of databases. It provides support for a JSON schema operator named as $jsonSchema that helps in validating the JSON documents. The $jsonSchema operator in MongoDB helps to perform several operations like insertion, deletion by following the specified JSON Schema.

In this article, we will provide an insight to use the $jsonSchema operator in MongoDB and the process to make the JSON Schema-based document is also provided. Let’s start this guide by understanding the JSON Schema followed by its working and use in MongoDB.

What is JSON Schema

It is a JSON document that helps to define the structure of a JSON message and can be used to validate the JSON documents. It can also be used to validate the API requests to check the format, datatypes of API requests as well. Usually, JSON Schema is created before any JSON message and it must be followed for any further supported actions. However, it can also be practiced after JSON documents too. If any JSON document or API request does not follow the specified JSON Schema, you will not be able to get the required output.

How to use $jsonSchema operator in MongoDB

The syntax to use $jsonSchema in MongoDB is provided below:

{$jsonSchema: <JSON Schema object>}

In our case, we have used the “customers” collection in a “linuxhint” database:

Example 1: Using $jsonSchema to define a schema for insert operation

Firstly, you must specify the $jsonSchema during the creation of Collection in MongoDB: For this, you have to follow the syntax mentioned below:

Syntax: (To set validation rules for a collection in MongoDB)

db.createCollection(<collection>, {validator: {$jsonSchema: <schema>}})

In the above syntax,

<collection> : Refers to the name that you will set for new collection

validator” : It is predefined keyword to initiate validation

<schema> : Contains the rules; for instance, the BSON types can be set for each field.

Following the syntax, we have created a “customers” collection and $jsonSchema operator is used to define schema validation rules in it:

db.createCollection("customers", {

validator: {

$jsonSchema: {

bsonType: "object",

required: [ "name", "year", "cat" ],

properties: {

name: {

bsonType: "string",

description: "name must be a string value"

},

year: {

bsonType: "int",

description: "must be an integer such as 2021)"

},

cat: {

bsonType: "string",

"description": "a string value"

}

}

}

}

})

Text Description automatically generated

Now the following command is used here to insert the specified fields in the “customers” collection. The command satisfies the JSON Schema validation rules:

> db.customers.insert({

name: "alen",

year: NumberInt(2021),

cat: "Author"

})

Text Description automatically generated

For instance, if the rules are not followed; the below mentioned command tries to insert an integer value in “cat” field: As the “cat” field can only accepts the “string” values, so, the Mongo query mentioned below will give an error:

> db.customers.insert({

name: "alen",

year: NumberInt(2021),

cat: NumberInt(123)

})

A picture containing timeline Description automatically generated

Example 2: Using $jsonSchema operator in reading MongoDB documents

With the help of $jsonSchema, you can find inserted documents that follows the JSON schema defined in query: You have to define the JSON Schema in your “find()” method of query:

In this example, “mycollection” is used and following documents resides inside it:

> db.mycollection.find().pretty()

Text Description automatically generated

We have created following schema object with the name of “linuxhintschema“:

let linuxhintschema = {

required: [ "name", "salary", "designation" ],

properties: {

name: { bsonType: "string" },

salary: { bsonType: "double" },

designation: { bsonType: "string" }

}

}

Text Description automatically generated

Now, to find the documents that follows the linuxhintschema rules; you can use the below mentioned command to do so:

> db.mycollection.find({$jsonSchema: linuxhintschema}).pretty()

Text Description automatically generated

Using $nor with $jsonSchema operator : Moreover, you can use $nor operator with $jsonSchema operator to find those documents that do not satisfy the specified schema:

> db.mycollection.find({$nor: [{$jsonSchema: linuxhintschema}]}).pretty()

Text Description automatically generated

Using $jsonSchema operator with $nor operator and Delete method : By using “$jsonSchema” with “$nor” and “Delete” method, you can delete the documents that do not satisfy the JSON schema (linuxhintschema) by using the command stated below:

> db.mycollection.deleteMany({$nor: [{$jsonSchema: linuxhintschema}]})

Conclusion

The database management systems are focused to manipulate the data of an organization effectively. The $jsonSchema operator is used to match the documents that follow the JSON schema rules; these rules are defined by users. Apart from retrieving, the $jsonSchema operator can be used to define the set of rules for insertion operation in MongoDB. Any insert query that satisfies the JSON Schema will be allowed to place data in the relevant collection.

About the author

Adnan Shabbir