MongoDB - Data Modeling

MongoDB - Data Modeling

Data in MongoDB has flexible schema.documents in the same collection. They don't have to have the same set of fields or structure, and common fields in collection documents can contain different types of data.

Some Considerations When Designing a Schema in MongoDB

  • Create your schema according to the user's requirements.

  • Merge objects into one document if you will be using them together. Separate them otherwise (but make sure no joins are needed).

  • Duplicate data (but limited) because disk space is cheap compared to computation time.

  • Do not join, but write, do not read.

  • Optimize your schema for the most common use cases.

  • Have a complex aggregation in a schema.

Create your schema according to the user's requirements.

Merge objects into one document if you will be using them together. Separate them otherwise (but make sure no joins are needed).

Duplicate data (but limited) because disk space is cheap compared to computation time.

Do not join, but write, do not read.

Optimize your schema for the most common use cases.

Have a complex aggregation in a schema.

example

Let's say a client needs a database design for their blog/website and you will see the differences between RDBMS schema design and MongoDB. The site has the following requirements.

  • Each post has a unique title, description and URL.
  • Each post can have one or more tags.
  • Each post has the name of its publisher and the total number of likes.
  • Each post has user comments, as well as their name, message, time, and likes.
  • Each post can have zero or more comments.

In an RDBMS schema, a project for the above requirements will have a minimum of three tables.

Designing an RDBMS Schema

Once in a MongoDB schema, the design will have one collection entry and the following structure:

{ 
   _id : POST_ID
   title : TITLE_OF_POST ,  
   description : POST_DESCRIPTION , by : POST_BY , 
   url : URL_OF_POST , 
   tags : [ TAG1 , TAG2 , TAG3 ], 
   likes : TOTAL_LIKES ,  
   comments : [ { 
         user : 'COMMENT_BY' , 
         message : TEXT , 
         dateCreated : DATE_TIME , 
         like
     	
      : LIKES 
       }, { 
         user : 'COMMENT_BY' , 
         message : TEXT , 
         dateCreated : DATE_TIME , 
         like : LIKES
       } ] }
      
   

Thus, when displaying data in an RDBMS, three tables need to be joined, while in MongoDB, data will only be displayed from one collection.