Latest web development tutorials

MongoDB relations

MongoDB relationship expressed interlinkages between multiple documents in logic.

You can establish contact by embedding and references between documents.

The MongoDB relationship can be:

  • 1: 1 (1 to 1)
  • 1: N (1-many)
  • N: 1 (multiple pairs 1)
  • N: N (many to many)

Next we consider the relationship between the user and the user's address next.

A user can have multiple addresses, it is one to many relationship.

The following is a simple user configuration document:

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

The following is a simple structure address document:

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

Embedded relations

Using the embedded method, we can embed the user's address to the user's 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"
      }]
} 

The above data is stored in a single document, you can more easily access and maintain data. You could query the user's address:

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

Note: The above querydb indicates database and usersand collections.

The disadvantage of this data structure is that if users and address the increasing amount of data becomes larger and larger, will affect the read and write performance.

Reference type relationship

Reference type relationship is often used in database design approach that user data files and user address data file separately to build relationships byid field reference document.

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

The aboveexample, address_ids document containing the object field of the user id of the user address (ObjectId) array.

We can read these objects id the user's address (ObjectId) to get detailed information about the user's address.

This method requires two queries, the first query object id user's address (ObjectId), the second address for more information on the user's query by id.

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