W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
聚合階段。將輸入記錄按給定表達式分組,輸出時每個記錄代表一個分組,每個記錄的 _id 是區(qū)分不同組的 key。輸出記錄中也可以包括累計值,將輸出字段設(shè)為累計值即會從該分組中計算累計值。
group 的形式如下:
group({
_id: <expression>,
<field1>: <accumulator1>,
...
<fieldN>: <accumulatorN>
})
_id 參數(shù)是必填的,如果填常量則只有一組。其他字段是可選的,都是累計值,用 $.sum 等累計器,但也可以使用其他表達式。
累計器必須是以下操作符之一:
該階段有 100M 內(nèi)存使用限制。
假設(shè)集合 avatar 有如下記錄:
{
_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()
返回結(jié)果如下:
{
"_id": "john",
"num": 3
}
{
"_id": "authur",
"num": 1
}
{
"_id": "george",
"num": 2
}
可以給 _id 傳入記錄的方式按多個值分組。還是沿用上面的示例數(shù)據(jù),按各個區(qū)域(region)獲得相同最高分(score)的來分組,并求出各組虛擬幣(coins)的總量:
const $ = db.command.aggregate
db.collection('avatar').aggregate()
.group({
_id: {
region: '$region',
maxScore: $.max('$scores')
},
totalCoins: $.sum('$coins')
})
.end()
返回結(jié)果如下:
{
"_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
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: