Member-only story
MongoDB Schema Validation Rules
How to apply schema validation rules in a collection
Short Intro
MongoDB is a very popular free and open source cross-platform document-oriented database. It is a NoSQL database and it is based on JSON-like documents. Document-based databases are either schema-less or they provide a certain level of flexibility defining schemas using schema validation rules.
For those who are coming from the RDBMS world, where a table structure is characterized by columns with strictly defined properties (type, size, etc.,), the ability to define schemas could be proved to be a quite useful option.
Generally, we can think that a MongoDB database object is similar to an RDBMS schema containing tables, views, and other RDBMS objects. Respectively, a MongoDB collection is analogous to a table, and a MongoDB document can be considered as a table row.
A MongoDB database can group together collections, a collection holds documents, and a document consists of a number of objects of key-value pairs, and even of other documents.
The purpose of this post is to demonstrate how we can apply some schema validation rules in a collection. For that, it is necessary to create an example MongoDB database with a MongoDB collection.
Prerequisites and Assumptions
Here, you can get an overview.
It is presumed that you have an available and accessible running MongoDB instance. If you don’t have this, then you can easily achieve that by also using Docker and the official MongoDB Docker image to run a MongoDB container. Read more at https://www.mongodb.com/compatibility/docker.
For convenience, we are also going to use the MongoDB Compass which is the official GUI for MongoDB.
Run a MongoDB Docker Container
You can create and run a Docker container named ‘mongodb’ by running the following command:
docker run --name mongodb -p 27017:27017 -d mongo
After you created the container, you can stop and start it using the following commands, respectively:
docker stop mongodb
docker…