May 20, 2021 WeChat Mini Program Development Document
Support: Small program 2.7.4, cloud function 0.8.1, Web
The aggregation phase. G roups of incoming collections based on incoming expressions. The number of different groups is then calculated, and the groups are sorted by the number of them, returning the results of the sort.
SortByCount is called as follows:
sortByCount(<表达式>)
The expression takes the form of: $ , specifying the field. Note: Don't miss the $ symbol.
Suppose the records for the collection passages are as follows:
{ "category": "Web" }
{ "category": "Web" }
{ "category": "Life" }
The following code counts the classification information for the article and calculates the number of categories. That is, the sortByCount aggregation is performed on the category field.
db.collection('passages')
.aggregate()
.sortByCount('$category')
.end()
The results are as follows: 2 articles under the Web category and 1 article under the Life category.
{ "_id": "Web", "count": 2 }
{ "_id": "Life", "count": 1 }
Suppose the record for the collection passages is as follows: the value for the tags field is the array type.
{ "tags": [ "JavaScript", "C#" ] }
{ "tags": [ "Go", "C#" ] }
{ "tags": [ "Go", "Python", "JavaScript" ] }
How do I count label information for an article and calculate the number of labels per label? Because of the array corresponding to the tags field, you need to deconstruct the tags field with the unwind operation, and then call sortByCount.
The following code does this:
db.collection('passages')
.aggregate()
.unwind(`$tags`)
.sortByCount(`$tags`)
.end()
The results returned are as follows:
{ "_id": "Go", "count": 2 }
{ "_id": "C#", "count": 2 }
{ "_id": "JavaScript", "count": 2 }
{ "_id": "Python", "count": 1 }