将评论和文章放在一起,这里我有一个疑问,当评论数量很大以后,会不会导致在查询文章列表页的时候效率低下?
如果将comments
剥离到另一个collection
里,这样是不是能缓解只显示文章列表的情况下的压力
{ "_id" : ObjectId(), "author" : "", "comment_num" : "", "comments" : [ { "text" : "", "created" : ISODate(), "author" : "" }, ], "created" : ISODate(), "text" : "", "title" : "" }
@halty makes a good point, don’t entirely agree with him. If there aren't many comments, the design put together is suitable, and what was said above is very good. But if there are too many comments, problems arise. The most important are two basic starting points: 1. The hard disk is too slow; 2. As long as the data is in memory, there is no problem.
When the data is extremely large, a lot of data needs to be read on the disk, because the Memory Mapped File will be stored in the memory, but we only need a small part of it. The main problem is that the OS may page other data to the hard disk. . Just for listing articles, memory is not used efficiently.
On a disk file, if a document keeps growing longer and longer, many times, this is not a good thing. Because if new data is added, for example, a new comment is added, the document becomes larger and cannot fit in the original place, so a new place has to be found, and the previous holes will be reused. But the problem is that when the document location changes, all indexes related to it must change. If you also have an index on the array, such as the name of the user who posted the comment, then the updated index will be linearly related to the length of the array.
The person above made a good point on this point. 16MB upper limit.
To sum up, when there are too many comments, it will affect the performance.
In summary, schema design should be considered
find
above is actually not a big problem. Because the comments on popular articles are always read by many people, it is good to store them in memory. If the document keeps getting longer, MongoDB will automatically allocate more disk space when allocating it.Having said that, I think most of these applications will not have more than a hundred comments... At this time, a single document will come into play. If there are hundreds of comments, it will be no problem, and the problem of the topic owner will not be a problem. I hope the author’s application can exceed this number...
First of all, make sure that when the number of comments is large, it will not lead to inefficiency when querying the article list page. You can specify that the document in the query result set only returns part of the field data (it should be noted that if you update and then save such a document that only contains part of the field data, an error may occur). This is recommended and can be done easily. Good at saving network bandwidth.
In addition, currently mongodb has a limit on the size of a single document. If there are too many comments, it may exceed the default size limit of the document. At this time, the comment needs to be stripped.