Relationships in MongoDB show how different documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N.
For example, consider a case of storing addresses for users. One user can have multiple addresses making this a 1:N relationship.
Below is the sample document structure of user document
Below is a sample document structure of address document
In the embedded approach, we will embed the address document inside the user document.
This approach will maintain all the related data in a single document, which makes it easy to retrieve and maintain. Whole document can be retrieved in a single query such as
Remember that in the above query, db and users are the database and collection respectively.
Drawback is that if the embedded document size grows too much, then it can impact the read/write performance.
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 which references the address document's id field.
As shown above, user document consists of array field address_ids which includes ObjectIds of corresponding addresses. Using these ObjectIds, address documents can be queried to get address details from there. You need two queries with this approach: one is to fetch the address_ids fields from user document and second is to fetch these addresses from address collection.
MongoDB Related Interview Questions
|Python Interview Questions||C & Data Structures Interview Questions|
|Hadoop Interview Questions||Node.js Interview Questions|
|Scala Interview Questions||Socket Programming Interview Questions|
|HBase Interview Questions||Solaris Administrator Interview Questions|
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.