This is my first my first post in this forum. I am from RDBMS background and wanted to learn MongoDB which will help me in migrating our applications to MongoDB. I am creating two collections (customer & address).
Customer collection
Has generic information like name,gender,city,country,phone, address (which should be reference to another collection).
Address collection
Has an array of information like current address, office address, mailing address. I wanted to know, how can I add a reference to another collection? Considering this scenario, Customer Collection will be having an Address document which will have to contain reference to ids in Address Collection.
If someone could provide me a sample example for this model. It would be great. Thank you in advance.
Best Answer
Relationships in
MongoDB
represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either1:1
,1:N
,N:1
orN:N
.It's possible through
Modeling Referenced Relationships
andDBRefs
.Here i am going to discuss about
Modeling Referenced Relationships
.Let us consider the case of storing addresses for customers. So, one customer can have multiple addresses making this a 1:N relationship.
Following is the sample document structure of customer document
Following is the sample document structure of address document −
Let's first i am going to write down here
Modeling Embedded Relationships
, for your better understanding.Even as @JJussi has already told that we can write down all documents information in one collection throughmodeling Embedded Relationship
.Modeling Embedded Relationships
Data in
MongoDB
has a flexible schema. Collections do not enforce document structure. Decisions that affect how you model data can affect application performance and database capacity.This document describes a data model that uses embedded documents to describe relationships between connected data.
If your application frequently retrieves the address data with the name information, then your application needs to issue multiple queries to resolve the references. A more optimal schema would be to embed the address data entities in the customer data, as in the following document:
Then Modeling Referenced Relationships
This is the approach of designing
normalized relationship
. In this approach, both thecustomer
andaddress
documents will be maintained separately but the customer document will contain a field that will reference theaddress
document'sid field
.As shown above, the customer document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from customer document and second to fetch these addresses from address collection.
For further your ref Here, Here and Here