MongoDB - Relationships

MongoDB - Relationships

Relationships in MongoDB represent how different documents are logically related to each other. Relationships can be modeled using inline and referential approaches. Such ratios can be 1:1, 1:N, N:1, or N:N.

Consider the case of storing addresses for users. So one user can have multiple addresses, making this a 1:N relationship.

The following is an example of the document structure of a custom document.

{ "_id" : ObjectId ( "52ffc33cd85242f436000001" ), "name" : "Tom Hanks" , "contact" : "987654321" , "dob" : "01-01-1991" }
   
    
    
    

Following is an example of address document document structure −

{ "_id" : ObjectId ( "52ffc4a5d85242602e000000" ), "building" : "22 A, Indiana Apt" , "pincode" : 123456 , "city" : "Los Angeles" , "state" : "California" }
   

Modeling built-in relationships

In the inline approach, we will embed the address document in 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" } ] }
          

With this approach, all related data is stored in a single document, making it easy to retrieve and maintain. The entire document can be retrieved in one request, for example:

>db.users.findOne({"name":"Tom Benzamin"},{"address":1})

Note that in the above query , db and users are the database and the collection, respectively.

The disadvantage is that if the size of the embedded document is too large, it can affect read/write performance.

Reference Relationship Modeling

This is the normalized relationship design approach. With this approach, the user and address documents will be stored separately, but the user document will contain a field that will refer to the address document ID field.

{ "_id" : ObjectId ( "52ffc33cd85242f436000001" ), "contact" : "987654321" , "dob" : "01-01-1991" , "name" : "Tom Benzamin" , "address_ids" : [ ObjectId ( "52ffc4a5d852420602e000 " ), ObjectId ( "52ffc4a5d85242602e000001" ) ] }
 


As shown above, the user document contains an address_ids array field that contains the ObjectIds of the corresponding addresses. Using these ObjectIds, we can query the address documents and get detailed information about the address from there. With this approach, we need two queries: the first to retrieve the address_ids fields from the user document, and the second to retrieve those addresses from the collection of addresses .