Schema Validation in MongoDB 3.6
Tags: mongodb, 36, schemavalidation
Published: 2017-11-28 21:49:25

---
title: "Schema Validation in MongoDB 3.6"
published: true
tags: MongoDB,3.6,Schema Validation
canonical_url: https://www.kenwalger.com/blog/nosql/mongodb/schema-validation-mongodb-3-6/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/jc105w09ospjy7v8vz45.png
---

MongoDB 3.6 brings lots of great new features with the new release. I’ve already covered [Change Streams](https://dev.to/kenwalger/change-streams-coming-soon-in-mongodb-36-967) and [Retryable Writes](https://dev.to/kenwalger/retryable-writes-in-mongodb-27l) in previous posts. This post will cover a feature which expands upon the [document validation](https://docs.mongodb.com/manual/core/document-validation/) feature from MongoDB 3.2, schema validation. Schema validation allows for teams to define a prescribed document structure for each collection.

There are times when enforcing strict data structures and content are required, even with the flexible schema and [document data model](https://www.kenwalger.com/blog/nosql/document-model/) that [MongoDB](https://www.mongodb.com) provides. Schema validation allows for the ability to define a prescribed document structure for each collection. If one tries to insert or update a document which does&nbsp;_not_ conform to the applied structure the operation can be rejected. The rules for document structure are based on the [J](http://json-schema.org/)[SON schema draft specification](http://json-schema.org/).

### Schema Validation

Let’s take a quick look at how this works in action before diving into a discussion of feature benefits.

Imagine a collection of food recipes. Each recipe will have a recipe name, number of servings, cooking method, ingredients, and list of instructions. For the&nbsp;ingredients, we&nbsp;want to enforce that there is a numerical quantity, a measure of quantity, the ingredient name, and an optional value for any prep work on the ingredient, such as “peeled” or “[brunoise](https://www.amazon.com/gp/product/0470421355/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0470421355&linkCode=as2&tag=kenwalgersite-20&linkId=d679d531adba3349c14bcf9f8a731651) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=0470421355)“.&nbsp; For our example here my options are not all-inclusive for options but simply serve as examples. I hope my former culinary colleagues forgive me.

We’ll begin with creating a `recipes` collection and assigning the schema validation rules with the `validator` option and the new [$jsonSchema](https://docs.mongodb.com/master/reference/operator/query/jsonSchema/#op._S_jsonSchema) operator.

```
db.createCollection( "recipes",
{
  validator: 
    {
      $jsonSchema:
        {
          bsonType: "object",
          required: ["name", "servings", "ingredients"],
          additionalProperties: false,
          properties:
            {
              _id: {},
              name: {
                bsonType: "string",
                description: "'name' is required and is a string"
                    },
              servings: {
                bsonType: ["int", "double"],
                minimum: 0,
                description: "'servings' is required and must be an integer greater than zero."
                    },
              cooking_method: {
                 enum: ["broil", "grill", "roast", "bake", "saute", "pan-fry", "deep-fry", "poach", "simmer", "boil", "steam", "braise", "stew"],
              description: "'cooking_method' is optional but, if used, must be one of the listed options."
                    },
              ingredients: 
              {
                bsonType: ["array"],
                minItems: 1,
                maxItems: 50,
                items: {
                  bsonType: ["object"],     
                  required: ["quantity", "measure", "ingredient"],
                  additionalProperties: false,
                  description: "'ingredients' must contain the stated fields.",
                  properties: 
                  {
                    quantity: {
                      bsonType: ["double", "decimal"],
                      description: "'quantity' is required and is of double or decimal type"
                            },
                    measure: {
                      enum: ["tsp", "Tbsp", "cup", "ounce", "pound", "each"],
                      description: "'measure' is required and can only be one of the given enum values"
                            },
                    ingredient: {
                      bsonType: "string",
                      description: "'ingredient' is required and is a string"
                            },
                    format: {
                      bsonType: "string",
                      description: "'format' is an optional field of type string"
                            }
                  }
              }
           }
        }
     }
   }
})
```

Our `validator` can include many [more rules](https://docs.mongodb.com/master/reference/operator/query/jsonSchema/#doc-insert-schema-validation) that are beyond the scope of this introduction to schema validation. However, we can see how powerful this feature is in this small example. Let’s look at some example documents to insert as well to see what would happen if we try to [insert](https://docs.mongodb.com/manual/reference/method/db.collection.insert/) a [document](https://docs.mongodb.com/manual/core/document/index.html) into the [collection](https://docs.mongodb.com/manual/core/databases-and-collections/index.html).

###### Sample Inserts

```
db.recipes.insertOne({name: "Chocolate Sponge Cake Filling", 
servings: 4, 
ingredients: [{quantity: 7, measure: "ounce", ingredient: "bittersweet chocolate", format: "chopped"}, 
{quantity: 2, measure: "cup", ingredient: "heavy cream"}
]})
```

This insert works since it covers all of the required fields in their proper format. It also doesn’t include any invalid extra fields which would be prohibited since we have&nbsp;`additionalProperties: false` set. If we were to try to insert the following document, however, we would get an error.

```
db.recipes.insertOne({name: "Chocolate Sponge Cake Filling", 
servings: 4, 
ingredients: [{quantity: 7, measure: "ounce", ingredient: "bittersweet chocolate", format: "chopped"}, 
{quantity: 2, measure: "cup", ingredient: "heavy cream"}],
directions: "Boil cream and pour over chocolate. Stir until chocolate is melted."
})
```

Since we added in a `directions` field into our recipe document, the insert will fail with&nbsp;`additionalProperties: false`&nbsp;set. I should add in an optional `directions` field into the schema validation to allow for that as directions are indeed important.

### Schema Validation Benefits

Even with these basic examples, I think it is clear that schema validation is a great new enhancement. The flexibility of a dynamic schema in MongoDB can now easily be paired with data governance controls over an entire collection. While there are lots of practical benefits from this, here are some specific benefits.

1. Application logic simplification. With a strictly defined definition of what a collection looks like, there isn’t a need for the application to handle the guarantees and associated errors.
2. Control of data. Client applications must adhere to the rules set forth by the collection. No need to worry about data being updated or inserted that has incorrect field names or data types.
3. Governmental compliance. There are applications and data models in a variety of industries and locales that require data to be stored in specific formats. For example, the [EU General Data Protection Regulation](https://www.amazon.com/gp/product/184928945X/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=184928945X&linkCode=as2&tag=kenwalgersite-20&linkId=da741c9e3ba84c6d499cac9f9a96a5bd) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=184928945X) in the European Union.

### Wrap Up

With MongoDB 3.6 schema validation, administrators have tunable controls over the database. Documents that don’t conform to a prescribed set of conditions can be rejected or still written and a message logged about the action. It also brings with it the ability to query based on the schema definition to allow,&nbsp;for example, a search on all documents that&nbsp;_don’t_ conform to the schema.

Schema validation is another exciting feature in the 3.6 release of MongoDB. I would urge you to [download](https://www.monogdb.com/download-center) it and try it out. I’d bet you’ll be as excited about it as I am.

* * *

Follow me on Twitter [@kenwalger](https://www.twitter.com/kenwalger) to get the latest updates on my postings. Or better yet, sign up for the email list to get updates in your mailbox!

There are a few MongoDB specific terms in this post. I created a [MongoDB Dictionary](https://www.echoskillstore.com/MongoDB-Dictionary/45103) skill for the [Amazon Echo](https://www.amazon.com/gp/product/B01DFKC2SO/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01DFKC2SO&linkCode=as2&tag=kenwalgersite-20&linkId=f9e513223de2525a72b95cf9561db55b)&nbsp;line of products. Check it out and you can say “Alexa, ask MongoDB for the definition of a&nbsp;document?” and get a helpful response.&nbsp;I also created a [culinary skill](https://www.echoskillstore.com/Kens-Culinary-Glossary/B072JXS3L5) for the Echo if you’d like to update your culinary knowledge as well.

[![Facebook](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&ssl=1 "Share on Facebook")](http://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F&t=Schema%20Validation%20in%20MongoDB%203.6&s=100&p%5Burl%5D=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F&p%5Bimages%5D%5B0%5D=https%3A%2F%2Fi2.wp.com%2Fwww.kenwalger.com%2Fblog%2Fwp-content%2Fuploads%2F2017%2F11%2Fdocument_validation_feature-e1511822206981.png%3Ffit%3D125%252C125%26ssl%3D1&p%5Btitle%5D=Schema%20Validation%20in%20MongoDB%203.6 "Share on Facebook")[![twitter](https://i0.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&ssl=1 "Share on Twitter")](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F&text=Hey%20check%20this%20out "Share on Twitter")[![google_plus](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/google_plus.png?resize=48%2C48&ssl=1 "Share on Google+")](https://plus.google.com/share?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F "Share on Google+")[![reddit](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/reddit.png?resize=48%2C48&ssl=1 "Share on Reddit")](http://www.reddit.com/submit?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F&title=Schema%20Validation%20in%20MongoDB%203.6 "Share on Reddit")[![linkedin](https://i2.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&ssl=1 "Share on Linkedin")](http://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F&title=Schema%20Validation%20in%20MongoDB%203.6 "Share on Linkedin")[![mail](https://i2.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/mail.png?resize=48%2C48&ssl=1 "Share by email")](mailto:?subject=Schema%20Validation%20in%20MongoDB%203.6&body=Hey%20check%20this%20out:%20https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-validation-mongodb-3-6%2F "Share by email")

The post [Schema Validation in MongoDB 3.6](https://www.kenwalger.com/blog/nosql/mongodb/schema-validation-mongodb-3-6/) appeared first on [Blog of Ken W. Alger](https://www.kenwalger.com/blog).