SDK數(shù)據(jù)庫 Aggregate·記錄分組

2022-05-12 16:47 更新

Aggregate.group(object: Object): Aggregate

支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web

聚合階段。將輸入記錄按給定表達式分組,輸出時每個記錄代表一個分組,每個記錄的 _id 是區(qū)分不同組的 key。輸出記錄中也可以包括累計值,將輸出字段設(shè)為累計值即會從該分組中計算累計值。

參數(shù)

object: Object

返回值

Aggregate

API 說明

group 的形式如下:

group({
  _id: <expression>,
  <field1>: <accumulator1>,
  ...
  <fieldN>: <accumulatorN>
})

_id 參數(shù)是必填的,如果填常量則只有一組。其他字段是可選的,都是累計值,用 $.sum 等累計器,但也可以使用其他表達式。

累計器必須是以下操作符之一:

  • 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:按多個值分組

可以給 _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
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號