databasemongodbdatabase-design

Mongodb comments, replies database analysis


In my application there are comments and replies; the comments will be stored in an array as sub-document for each array-item.

To store replies, I'm thinking about two cases.

  1. store replies in an embedded array in same comment sub-document

     comments : [
         { 
             commentId: ObjectId("XXXX"),
                 ...
             replies : [
                 { 
                 replyId : ObjectId("XXX") 
                 ...
                 } 
               ]
         } 
        ]
    
  2. new array (replies); each element is a sub-document of a reply

     {
         comments :[ .....] ,
         replies: [ 
                 {
                 commentId: ObjectId("XXX"), 
                 replies : [ ...]
                 }
         ]
     }
    

Solution

  • Approach 1

    Pros : Retrieval is very fast and it is aligned what MongoDB document concept and best practices. Only document you need to update and it will be faster

    Cons : The Document size will grow with each activity and may reach to 16MB hard limit. if you are sure that comment and reply is very much limited then it is fine.

    Approach 2

    Pros : If you want to load replies to comment on the request of the user it will be good because your document with the comment will be light weighted and will be much in control in the data size

    Cons : With MongoDB 4.0 we have multi document transaction support which was not supported earlier which used to create issue if you are able to update the reply but while updating the Comment error occurred. 2nd is that each update you still need to update 2 documents.

    So approach 1 or 2 both depend on your use case. If the Comments and Replies are limited Approach 1 will be must better other wise Approach 2 with Mongodb 4.0 transaction support.