MongoDB Relationships

MongoDB relationships represent the logical connections between multiple documents.

Documents can be linked through embedding and referencing.

Relationships in MongoDB can be:

  • 1:1 (one-to-one)
  • 1: N (one-to-many)
  • N: 1 (many-to-one)
  • N: N (many-to-many)

Next, let's consider the relationship between users and user addresses.

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

The following isuserthe simple structure of the document:

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

The following isaddressthe simple structure of the document:

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

Embedded Relationships

Using the embedded method, we can embed user addresses into 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, making it easier to retrieve and maintain data. You can query the user's address like this:

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

Note: In the above query,dbandusersrepresents the database and collection.

The disadvantage of this data structure is that if users and user addresses keep increasing and the data volume keeps growing, it will affect read and write performance.

Referenced Relationships

The referenced relationship is a method often used when designing databases. This method separates the user data document from the user address data document, by referencing the document'sidfield to establish the relationship.

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

In the above example, the user document'saddress_idsfield contains an array of ObjectIds of the user addresses.

We can read these user address ObjectIds to obtain the user's detailed address information.

This method requires two queries. The first query retrieves the ObjectIds of the user addresses, and the second query uses the retrieved ids to obtain the user's detailed address information.

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