MongoDB Data Structure

MongoDB Data Structure

In today’s topic, we are going to cover MongoDB Data Structure. The Main challenge while defining the data structure in database is need of application and same time we need to consider performance while retrieving the data.

In SQL Databases, you need to define table’s schema before doing any operations like inserting , retrieving etc. Where in MongoDB doesn’t require to define any schema and doesn’t require to have same schema in documents in same collection.

Data Structure Design

MongoDB Supports two types of data models

  • Embedded Data Model
  • Normalized Data Model

Embedded Data Model

In Embedded Data Model, you can have all related data in a single collection, you don’t need to maintain different collection.

Example : Suppose you have customer informations in 2 different documents like , customer info , customer address. So you can embed these 2 documents in single document as below

{
	_id: ObjectId('635948266d4a86244ef262b2'),	 
	Customer_Info:{
		firstname: "Hitesh",
		lastname: "Agrawal",
                email: "hiteshagrawal84@gmail.com		 
	}	 
	Customer_Address: {
		city: "Ahmedabad",
		State: "Gujarat",
		Country: "India"
	}
}

Normalized Data Model

This data model is same like sql normalized one where you need to define foriegn key and make a relation between 2 tables , so in mongodb you can use object id of one table to another table.

Below is example for same.

Customer Info Collection

{
	_id: ObjectId('635948266d4a86244ef262b2'), 
	firstname: "Hitesh",
	lastname: "Agrawal",
        email: "hiteshagrawal84@gmail.com	 
}

Customer Address

{
	_id: ObjectId('63595cf5bc5e4d54f2c7d891'), 
	customer_id: ObjectId('635948266d4a86244ef262b2'),
	city: "Ahmedabad",
	State: "Gujarat",
	Country: "India"	 
}

Here you can see that, I have created 2 collection, first one is for customer info and 2nd collection is for customer address where I have mentioned customer_id which is the object id from customer info table.

Hope you like my this blog so please share with your friends and visit us again.

Leave a Reply
Your email address will not be published. *