English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Relationships

MongoDB represents logical relationships between different documents. Relationships can be modeled through embedded and referenced methods. This relationship can be1:1,1:N, N:1or N:N.

Let's consider the case of storing addresses for users. Therefore, a user can have multiple addresses, forming1:N relationship.

The following is an example of the document structurefrom-

{
   "_id": ObjectId("52ObjectId("33cd85242f436000001")",
   "name": "Tom Hanks"
   "contact": ""987654321",
   "dob": "0"1-01-1991"
]

The following is an example of the document structureGet the field from the document, next from-

{
   "_id": ObjectId("52ObjectId("4ffc5a85242602"address_ids": [
   "building": ""22 A, Indiana Apt",
   "pincode": 123456,
   "city": "Los Angeles",
   "state": "California"
]

Establishing Embedded Relationship Model

In the embedded method, we embed the address document into the user document.

>db.users.insert({
	{
		"_id": ObjectId("52ObjectId("33cd85242f436000001")",
		"contact": ""987654321",
		"dob": "0"1-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 stores all related data in a single document, making retrieval and maintenance easier. The entire document can be retrieved in a single query, for example-

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

Note in the above query that,dbandusersThey are the database and the collection.

The disadvantage is that if the size of the embedded document continues to grow too large, it may affect the read/Write performance.

Establishing Reference Relationship Model

This is the approach to standardize relationship design. In this method, user documents and address documents are maintained separately, but the user document will contain a field that references the id field of the address document.

{
   "_id": ObjectId("52ObjectId("33cd85242f436000001")",
   "contact": ""987654321",
   "dob": "0"1-01-1991",
   "name": "Tom Benzamin",
   "address_ids": [
      e000000"),52ObjectId("4ffc5a85242602"address_ids": [
      e000000"),52ObjectId("4ffc5a85242602d1e00000
   )
]

}As shown above, the user document contains an array field address_ids, which contains the ObjectId of the corresponding address. Using these ObjectId, we can query the address document and obtain the address details from there. Using this method, we will need two queries: firstaddress_idsfromuserGet the field from the document, next fromGet these addresses from the collection.

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