Specify Allowed Field Values in MongoDB
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
- Create a Collection with Validation Containing an βenumβ Keyword in JSON Schema.
- Confirm that the Validation Prevents Invalid Documents.
- Insert a Valid Document.
- 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:
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.
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.
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:
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.