May 20, 2021 WeChat Mini Program Development Document
Support: Small program 2.7.4, cloud function 0.8.1, Web
The aggregation phase. G roup input records by a given expression, and each record represents a group at output, and the _id for each record is key that distinguishes between different groups. Cumulative values can also be included in the output record, and setting the output field to cumulative values calculates cumulative values from that grouping.
The group takes the form of:
group({
_id: <expression>,
<field1>: <accumulator1>,
...
<fieldN>: <accumulatorN>
})
_id parameters are required, and if you fill in the constant, there is only one set. Other fields are optional, are cumulative values, with accumulators such as $.sum, but other expressions can also be used.
The accumulator must be one of the following operators:
There is a 100M memory usage limit for this phase.
Suppose the collection avatar has the following records:
{
_id: "1",
alias: "john",
region: "asia",
scores: [40, 20, 80],
coins: 100
}
{
_id: "2",
alias: "arthur",
region: "europe",
scores: [60, 90],
coins: 20
}
{
_id: "3",
alias: "george",
region: "europe",
scores: [50, 70, 90],
coins: 50
}
{
_id: "4",
alias: "john",
region: "asia",
scores: [30, 60, 100, 90],
coins: 40
}
{
_id: "5",
alias: "george",
region: "europe",
scores: [20],
coins: 60
}
{
_id: "6",
alias: "john",
region: "asia",
scores: [40, 80, 70],
coins: 120
}
const $ = db.command.aggregate
db.collection('avatar').aggregate()
.group({
_id: '$alias',
num: $.sum(1)
})
.end()
The results are as follows:
{
"_id": "john",
"num": 3
}
{
"_id": "authur",
"num": 1
}
{
"_id": "george",
"num": 2
}
You can group _id values in the way you pass in records to your organization. Using the example data above, group by region to get the same highest score, and find out the total amount of each set of virtual coins:
const $ = db.command.aggregate
db.collection('avatar').aggregate()
.group({
_id: {
region: '$region',
maxScore: $.max('$scores')
},
totalCoins: $.sum('$coins')
})
.end()
The results are as follows:
{
"_id": {
"region": "asia",
"maxScore": 80
},
"totalCoins": 220
}
{
"_id": {
"region": "asia",
"maxScore": 100
},
"totalCoins": 100
}
{
"_id": {
"region": "europe",
"maxScore": 90
},
"totalCoins": 70
}
{
"_id": {
"region": "europe",
"maxScore": 20
},
"totalCoins": 60
}