WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

>MongoDB - Relationships


MongoDB - Create Collection: In this chapter Relationships in MongoDB.

Relationships can be either 1:1, 1:N, N:1 or N:N

Let us consider the case of storing addresses for users.

Following is the sample document structure of user document

{
   "_id":ObjectId("541221455412"),
   "name": "ADITYA",
   "contact": "565114",
   "dob": "01-01-1975"
}
is the sample document structure of address document
{
   "_id":ObjectId("21215412154"),
   "building": "22 A, Indiana Apt",
   "pincode": 123456,
   "city": "LA",
   "state": "CA"
} 

Modeling Embedded Relationships

In the embedded approach, we will embed the address document inside the user document.
{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Tom Benzamin",
   "address": [
      {
         "building": "22 A, Indiana Apt",
         "pincode": 123456,
         "city": "Los Angeles",
         "state": "California"
      },
      {
         "building": "170 A, Acropolis Apt",
         "pincode": 456789,
         "city": "Chicago",
         "state": "Illinois"
      }
   ]
} 

Modeling Referenced Relationships

This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field.
{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Tom Benzamin",
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}
This is the approach of designing normalized relationship. In this approach
>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})




Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.