新聞中心
Aggregate.group(object: Object): Aggregate
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
為秦淮等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及秦淮網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)、秦淮網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
聚合階段。將輸入記錄按給定表達(dá)式分組,輸出時(shí)每個(gè)記錄代表一個(gè)分組,每個(gè)記錄的 _id 是區(qū)分不同組的 key。輸出記錄中也可以包括累計(jì)值,將輸出字段設(shè)為累計(jì)值即會(huì)從該分組中計(jì)算累計(jì)值。
參數(shù)
object: Object
返回值
Aggregate
API 說明
group 的形式如下:
group({
_id: ,
: ,
...
:
})
_id 參數(shù)是必填的,如果填常量則只有一組。其他字段是可選的,都是累計(jì)值,用 $.sum 等累計(jì)器,但也可以使用其他表達(dá)式。
累計(jì)器必須是以下操作符之一:
- addToSet
- avg
- first
- last
- max
- min
- push
- stdDevPop
- stdDevSamp
- sum
內(nèi)存限制
該階段有 100M 內(nèi)存使用限制。
示例 1:按字段值分組
假設(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
}
示例 2:按多個(gè)值分組
可以給 _id 傳入記錄的方式按多個(gè)值分組。還是沿用上面的示例數(shù)據(jù),按各個(gè)區(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
} 分享文章:創(chuàng)新互聯(lián)小程序教程:SDK數(shù)據(jù)庫Aggregate·記錄分組
分享路徑:http://www.dlmjj.cn/article/djshdgc.html


咨詢
建站咨詢

