Tuesday 14 February 2017

Maintaining Relationship in NoSQL

The decision "What database to use" is a bit difficult. Most Startup rely on NoSQL Database. MongoDB is the most popular NoSQL DataBase. NoSQL Database has grown in popularity due to it's open source, flexible in nature and ease to use.

But what about relationship

As Database is mostly representation of real world entities relationship is very important to be maintain among database. While MongoDB is not a relational database, there are two recommended approaches to representing relationships between entities.

Modeling Embedded Relationships

In this approach we embed the related document inside its parent document.

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   ...
   "address": [
      {
         "building": "22 A, Indiana Apt",
         ...
      },
      {
         "building": "ABC Apart",
         ...
      }
   ]
} 

This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. But The drawback is it is not Consistent. And if the embedded document keeps on growing too much in size, it can impact the read/write performance.

Modeling Referenced Relationships

In this approach the two related table are maintained saperatly and the reference of one table is maintained in another table by its document id

{
   ...
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}

The benefit of this approach is whenever a document is updated, there is no overhead of managing other document because the reference ids does not change and the problem of Consistency is solved.

No comments:

Post a Comment