Mongodb aggregate query?

  mongodb, question

Only one piece is in the front end. I didn’t contact the background database before. Now I am learning mongodb database. When I meet such a situation, I build a blog database. There is such a collection containing all the article information. The data forgery is as follows:

{ "id" : 1, "name" : "one", "tags" : [ "a", "c", "e" ] }
 { "id" : 2, "name" : "two", "tags" : [ "e" ] }
 { "id" : 3, "name" : "three", "tags" : [ "d", "e" ] }
 { "id" : 4, "name" : "four", "tags" : [ "g", "c", "e", "h" ] }
 { "id" : 5, "name" : "five", "tags" : [ "a", "c", "d" ] }

Tags indicates the tag type to which this article belongs. Now how many different tag types do you want to find out, how many pieces of data are under each tag, and how to realize this? At present, the idea is to use $unwind in aggregate to split tags, and then use $group for grouping statistics. However, how to write the specific code, or there are other more effective ways, please advise! ! !

This is a very classic statistical problem. Actually, it is no longer a unique category of MongoDB and is also common to other databases.
There is no problem with the way you think, and you can definitely go through aggregation.$unwind+$groupGet the results you want. The problem is that as time goes by, the number of blogs participating in the statistics will increase, which means that your statistics will be slower and slower. The crux of the problem lies in how to limit the number of records each time.
From another point of view, blogs are rarely changed after they are written. Statistics on which tags all blogs belong to yesterday today should be the same as statistics on yesterday tomorrow (assuming there is no change). So it is a waste to make statistics every time.
Based on the above considerations, you can actually count how many times each label appears every other period of time (e.g. every day), save them, and aggregate the aggregated data again when necessary. This method is called prepolymerization.
The general direction is this: you can think about the details first.