Enum in MongoDB

Enums can be used to set predefined or expected values. If you set the validation settings to output errors (see the item 1 on the screenshot below), inserting data will cause an error if you try to insert a record that does not match the schema specification.

How to define Enum in MongoDB Projects

In MongoDB projects created in Moon Modeler, enums can be defined in the same way as any other data type.
In the selected collection, just pick the Enum data type (2) for the field and then set the values in the Enum input (3).

MongoDB Enum definition in Moon Modeler
db.createCollection('traffic', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      title: 'traffic',
      properties: {
        source: {
          enum: ['campaign', 'website', null]
        },
        data: {
          bsonType: 'object',
          title: 'object',
        }
      }
    }
  },
  validationLevel: 'strict',
  validationAction: 'error'
});

Inserting a record that matches the enum specification

If we insert a record that matches the schema, the data insertion will be successful.

db.traffic.insertOne({source: 'campaign', data: {campaign: 'test'}});
MongoDB enum and output of successful record insertion

Inserting a record that does not match the enum specification

If the record contains values that are not defined in the enum, then the insert may fail. Of course, it depends on the settings of the data validation method in MongoDB.

The following command contains the value ‘google ads‘. This value is not listed in the enumeration and therefore the validation will fail.

db.traffic.insertOne({source: 'google ads', data: {campaign: 'test'}});
MongoDB enum and validation that outputs an error.

 #

Quick links

Free Trial Buy Now!

Blog Categories
Blog by Platforms