Home >>MongoDB Tutorial >MongoDB Relationships

MongoDB Relationships

Relationships in MongoDB

Relationships in MongoDB represent how different documents are related to each other logically. Through Embedded and Referenced approaches, relationships can be modelled. Either 1:1, 1:N, N:1 or N:N may be such relationships.

Let us consider the case of storing users' addresses. Therefore one user can have many addresses that make this a 1:N relationship.

The following is the user document sample document structure –

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "name": "Phptpoint Hanks",
   "contact": "9876455702",
   "dob": "01-08-1993"
}

Following is the sample document structure of address document −

{
   "_id":ObjectId("52ffc4a5d85242602e000000"),
   "building": "57 C, Indiana Apt",
   "pincode": 123796,
   "city": "Los Angeles",
   "state": "California"
} 

Modeling Embedded Relationships

We will embed the address document within the user document in the embedded approach.

> db.users.insert({
	{
		"_id":ObjectId("52ffc33cd85242f436000001"),
		"contact": "987654321",
		"dob": "01-07-1993",
		"name": "Tom Benzamin",
		"address": [
			{
				"building": "57 C, Indiana Apt",
				"pincode": 123456,
				"city": "Los Angeles",
				"state": "California"
			},
			{
				"building": "170 A, Acropolis Apt",
				"pincode": 456789,
				"city": "Chicago",
				"state": "Illinois"
			}
		]
	}
})

This method maintains in a single document all the related data, which makes it easy to retrieve and retain. You can retrieve the entire document in a single query, such as –

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

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

The drawback is that it can affect the read/write performance if the embedded document continues to grow too much in size.

Modeling Referenced Relationships

This is the technique of standardized relationship development. Both the user and address documents will be maintained separately in this approach, but the user document will include a field that will reference the ID field of the address document.

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

The user document contains the array field address ids representing ObjectIds of the corresponding addresses as shown above. We can query the address documents using these ObjectIds and obtain address information from there. We will need two queries for this approach: first to fetch the address id fields from the user document and second to fetch these addresses from the list of addresses.

>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})

No Sidebar ads