Open In App

Specify Allowed Field Values in MongoDB

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB was released in February 2009. It is an open-source document-oriented database. It is classified as a NoSQL database. Its schema is dynamic and is unstructured language. It follows the CAP theorem (Consistency Availability and Partition tolerance). It provides horizontal scalability and high-performance data persistence. It solved the problem of scalability and agility. It also can handle complex, large, and unstructured data. It is the most widely used NoSQL Database.

What are Allowed Field Values?

Allowed field Values are the list of the values that the field may have. The Allowed field specifies that only certain types of values are allowed and nothing else is permitted. Using JSON Schema you can specify allowed values a particular field may have. The ‘enum keyword is used to specify these allowed field values in JSON Schema. For example, if the marital status is a field and the allowed values specified using the enum keyword are Single and Married then the field should contain the mentioned value only. Allowed values are countable. These values are displayed with the help of dropdown options or radio buttons in real-time applications. It limits the allowed values for the particular field. Allowed field values reduce the scope of human error such as entering invalid data or typos.

Need to Specify Allowed Field Values?

It allows Database Administrators (DBA) to ensure the value stored is accurate and consistent. It provides a clear expectation of data for a particular field. Allowed values are consistent across all the documents. It ensures that only allowed values are in the database. It applies additional schema validation on the field value. It helps to efficiently request for the documents. It reduces the error helps to adapt to changing business rules and increases system performance.

Steps to Specify Allowed Field Values

  1. Create a Collection with Validation Containing an ‘enum’ Keyword in JSON Schema.
  2. Confirm that the Validation Prevents Invalid Documents.
  3. Insert a Valid Document.
  4. Query for the Valid Document.

1. Create a Collection with Validation Containing an ‘enum’ Keyword in JSON Schema.

In this step, the collection is created with a Validation rule and an enum keyword to specify the allowed field values. enum keyword list the allowed values for the particular field in a collection.

Syntax:

use database_name;
db.createCollection('collection_name
{ validator: { $jsonSchema :
{ bsonType:'object', required : [' fields that must be present '],
properties: { field_name : {bsonType : 'specify_type' , enum:[ alllowed_field_value ] ,description: ''Specify description } } } } } );

Explanation:

  • use database_name‘ is used to name the database which we use.
  • The ‘createCollection( )‘ method is used to prepare a collection with a particular name.
  • validator‘ is used to specify the validation rule which contains bsonType, required field, enum , minimum, or maximum.
  • required‘ specifies the fields that must be present in the document.
  • properties‘ is an object for defining each field.
  • bsonType‘ specifies the datatype of the field.
  • enum is used to list the allowed values of the field.
  • description‘ is used to describe the characteristics of the field.

Example:

Create-a-collection-with-validation-containing-an-enum-keyword-in-JSON-Schema

Create a collection with validation containing an enum keyword in JSON Schema

Explanation: In the above example, schema for the ‘student‘ collection is defined. For the ‘maritalStatus field allowed field values are specified using the ‘enum keyword, the allowed field value are [‘Single’ ,’Married’].

2. Confirm that the Validation Prevents Invalid Documents

This step prevent invalid document from entering it in a collection. Invalid document don’t satisfy the validation rule specified in the schema.

Example:

  • insertOne()‘ is used to insert one document in the collection.
Confirm-that-the-validation-prevents-invalid-documents

Confirm that the validation prevents invalid documents.

Explanation: In the example mentioned , as per the validation rule there are two specified allowed values for the ‘maritalStatus‘ field but other value than the specified field value was used . Hence validation rule failed during insertion of the document which caused an error. Error contains various details such as the ‘propertyname‘ which does not satisfy the value, reason, description of the file, and many more details.

3. Insert a Valid Document

In this step, the document is inserted according to the validation rules. Document gets inserted successfully into the collection. This document is known as valid document.

Example:

  • insertMany()‘ is used to insert more than one document in the collection.
Insert-a-valid-document

Insert a valid document.

Explanation: In the above example, values used in the documents are according to the allowed field values. Hence the documents are successfully inserted into the collection.

4. Query for the Valid Document

Validation rules prevent invalid documents. Hence collection has valid documents in it. In this step, documents in the collection are displayed using the find() method.

Syntax:

db.collection_name.find( );

Example:

Query-for-the-valid-document

Query for the valid document.

Explanation: In the example mentioned above, entries in the collection are requested hence as two documents are inserted they are displayed.

Conclusion

Setting Allowed field values is good practice to prevent errors and ensure data integrity. It is like predefining the allowed values for a particular field. Allowed values are specified using the enum keyword in validation schema. The validation rule prevents invalid document from insertion into the collection and allows the valid document.The documents inserted successfully are requested and hence the process completes.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads