How to perform Data Modelling in MongoDB?

MongoDB has a flexible schema. MongoDB provides two types:

  • Embedded Data Model
  • Normalized Data Model.

With MongoDB, you may embed related data in a single structure or document. These schemas are generally known as “denormalized” models. Embedded data models allow applications to store related pieces of information in the same database record.

{

           _id:<ObjectId1>,

username: “123xyz”,

contact: {

           phone: “123-456-7890”,
           email: xyz@example.com

         },

access: {
            level: 5,

            group: “dev”

        }

}

Normalized data models describe relationships using references between documents. In general, we use a normalized data model when embedding would result in duplication of data but would not provide sufficient read performance advantages to outweigh the implications of the duplication. Again, the normalized data model has been used to represent more complex many-to-many relationships. It is also used to model large hierarchical datasets.

User document:

  {

    _id:<ObjectId1>,

    username: “123xyz”

}

Contact documents:

   {

     _id: <ObjectId2>,

     user_id: <ObjectId1>,

     phone: “123-456-7890”,

      email: “xyz@example.com”

}

Access document:

  {

      _id: <ObjectId3>,

      user_id: <ObjectId1>,

      level: 5,

      group: “dev”

}