How to use MongoDB Shell In JSON

The MongoDB Shell approach directly interacts with the MongoDB server to create collections with schema validation.

Steps:

  • Connect to your MongoDB server using the shell.
  • Execute the db.createCollection command with the validator option to define your JSON Schema.

Example:

Microsoft Windows [Version 10.0.22631.3593]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Jeetu>mongosh
Current Mongosh Log ID: 664c29b41fa4c614a5def71c
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.1.5
Using MongoDB: 7.0.6
Using Mongosh: 2.1.5
mongosh 2.2.6 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

The server generated these startup warnings when booting
2024-05-20T22:25:15.613+05:30: Access control is not enabled for the database.
Read and write access to data and configuration is unrestricted


test> use myDatabase;
switched to db myDatabase
myDatabase> db.createCollection("users", {
... validator: {
... $jsonSchema: {
... bsonType: "object",
... required: ["name", "age"],
... properties: {
... name: {
... bsonType: "string",
... description: "must be a string and is required"
... },
... age: {
... bsonType: "int",
... minimum: 0,
... description: "must be an integer greater than or equal to 0
and is required"
... }
... }
... }
... }
... });
{ ok: 1 }
myDatabase> db.users.insertOne({ name: "Alice", age: 25 });
{
acknowledged: true,
insertedId: ObjectId('664c29c81fa4c614a5def71d')
}
myDatabase> db.users.insertOne({ name: "Bob" });
Uncaught:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId('664c29d11fa4c614a5def71e'),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'required',
specifiedAs: { required: [ 'name', 'age' ] },
missingProperties: [ 'age' ]
}
]
}
}
myDatabase> db.users.insertOne({ name: "Charlie", age: "twenty-five" });
Uncaught:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId('664c29d81fa4c614a5def71f'),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'age',
description: 'must be an integer greater than or equal to 0 and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'int' },
reason: 'type did not match',
consideredValue: 'twenty-five',
consideredType: 'string'
}
]
}
]
}
]
}
}
myDatabase> db.users.insertOne({ name: "Dave", age: -5 });
Uncaught:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId('664c29e21fa4c614a5def720'),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'age',
description: 'must be an integer greater than or equal to 0 and is required',
details: [
{
operatorName: 'minimum',
specifiedAs: { minimum: 0 },
reason: 'comparison failed',
consideredValue: -5
}
]
}
]
}
]
}
}

How to Create and Validate JSON Schema in MongoDB?

JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated.

In this article, we will cover how to create and validate JSON Schema in MongoDB using different approaches, provide a step-by-step guide to set up the application, and include an example for better understanding.

Validating JSON schema involves defining the required schema and creating a model in Mongoose. We can validate the JSON Schema in MongoDB using the approaches mentioned below:

Table of Content

  • Creating JSON Schema
  • Using MongoDB Shell
  • Using Mongoose

Similar Reads

Creating JSON Schema

Using MongoDB Shell...

Using MongoDB Shell

The MongoDB Shell approach directly interacts with the MongoDB server to create collections with schema validation....

Using Mongoose

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js....