Relationships in MongoDB represent how numerous documents are logically related to each different. Relationships can be modeled thru Embedded and Referenced methods. Such relationships can be both 1:1, 1:N, N:1 or N:N.
Let us don't forget the case of storing addresses for users. So, one user will have a couple of addresses making this a 1:N dating.
Following is the pattern file structure of consumer document −
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"name": "Tom Hanks",
"contact": "987654321",
"dob": "01-01-1991"
}
Following is the sample file shape of cope with document −
{
"_id":ObjectId("52ffc4a5d85242602e000000"),
"building": "22 A, Indiana Apt",
"pincode": 123456,
"city": "Los Angeles",
"state": "California"
}
Modeling Embedded Relationships
In the embedded approach, we will embed the deal with record inside the user report.
> db.users.insert({
{
"_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"
}
]
}
})
This method continues all the associated information in a unmarried document, which makes it clean to retrieve and hold. The entire report may be retrieved in a single question together with −
>db.users.findOne({"name":"Tom Benzamin"},{"address":1})
Note that in the above question, db and users are the database and series respectively.
The disadvantage is if the embedded report keeps on developing too much in length, it may impact the examine/write performance.
Modeling Referenced Relationships
This is the method of designing normalized courting. In this method, each the consumer and deal with files can be maintained separately but the user report will incorporate a field in order to reference the address record's identification area.
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin",
"address_ids": [
ObjectId("52ffc4a5d85242602e000000"),
ObjectId("52ffc4a5d85242602e000001")
]
}
As proven above, the user file incorporates the array discipline address_ids which includes ObjectIds of corresponding addresses. Using those ObjectIds, we will query the address files and get cope with details from there. With this approach, we will want two queries: first to fetch the address_ids fields from consumer file and 2nd to fetch those addresses from cope with series.
>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})