简体   繁体   中英

MongoDB: Embedded Documents vs Multiple Collections

I have to modelize my data in a MongoDB database. My data are posts and comments, so the approachs I have thought are two:

  1. 1 collection of status with the comments embedded in each status

  2. 1 collection of status and 1 collection of comments

Consider that, from the user experience side, the user sees a list of status, and he just sometimes asks for seeing the comments of a given status. Consider also that the user could ask to see the comments of a given user: if the comments are embedded in statuses it could be more expensive to retrieve these information.

Which solution do you suggest?

Thank you!

It's depends of comments count and really frequency of requests. Because if you will have a few comments, you should not think about it. Also, if you will use two collections, queries will be more complicated and with big size of comments collection will works slowly, than one select from one collection. Actually, denormalization it's good way for storing data in MongoDB.

By looking at the solution and related query I think , you have to consider the frequency of kind of query going to happen. One point is applicable that , one design can not solve all the problem without causing some issue. For example if in real time the people looking for comments related to status more and much more in compare to see the all the comments from a user . I think embedding the comments in the status is going to have better user experience . As mongodb allow indexing of subdocument if you can have this kind of schema

         Status : " I am good",
         Comments : [{ Comment : "great" , by : "UserOne" } , [{ Comment : "great" , by : "UserOne" }]

you can index the Comments.by So the search of all the comments by a user will also be good . While fetching the status you can cahce the Comments and get the comments from the cache to make User experience better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM