SDK數(shù)據(jù)庫 Aggregate·劃分輸入數(shù)據(jù)

2022-05-12 16:45 更新

Aggregate.bucket(object: Object): Aggregate

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

聚合階段。將輸入記錄根據(jù)給定的條件和邊界劃分成不同的組,每組即一個 bucket。

參數(shù)

object: Object

返回值

Aggregate

API 說明

每組分別作為一個記錄輸出,包含一個以下界為值的 _id 字段和一個以組中記錄數(shù)為值的 count 字段。count 在沒有指定 output 的時候是默認輸出的。

bucket 只會在組內(nèi)有至少一個記錄的時候輸出。

bucket 的形式如下:

bucket({
  groupBy: <expression>,
  boundaries: [<lowerbound1>, <lowerbound2>, ...],
  default: <literal>,
  output: {
    <output1>: <accumulator expr>,
    ...
    <outputN>: <accumulator expr>
  }
})

groupBy 是一個用以決定分組的表達式,會應用在各個輸入記錄上??梢杂?nbsp;$ 前綴加上要用以分組的字段路徑來作為表達式。除非用 default 指定了默認值,否則每個記錄都需要包含指定的字段,且字段值必須在 boundaries 指定的范圍之內(nèi)。

boundaries 是一個數(shù)組,每個元素分別是每組的下界。必須至少指定兩個邊界值。數(shù)組值必須是同類型遞增的值。

default 可選,指定之后,沒有進入任何分組的記錄將都進入一個默認分組,這個分組記錄的 _id 即由 default 決定。default 的值必須小于 boundaries 中的最小值或大于等于其中的最大值。default 的值可以與 boundaries 元素值類型不同。

output 可選,用以決定輸出記錄除了 _id 外還要包含哪些字段,各個字段的值必須用累加器表達式指定。當 output 指定時,默認的 count 是不會被默認輸出的,必須手動指定:

output: {
  count: $.sum(1),
  ...
  <outputN>: <accumulator expr>
}

使用 bucket 需要滿足以下至少一個條件,否則會拋出錯誤:

  • 每一個輸入記錄應用 groupBy 表達式獲取的值都必須是一個在 boundaries 內(nèi)的值
  • 指定一個 default 值,該值在 boundaries 以外,或與 boundaries 元素的值不同的類型。

示例

假設集合 items 有如下記錄:

{
  _id: "1",
  price: 10
}
{
  _id: "2",
  price: 50
}
{
  _id: "3",
  price: 20
}
{
  _id: "4",
  price: 80
}
{
  _id: "5",
  price: 200
}

對上述記錄進行分組,將 [0, 50) 分為一組,[50, 100) 分為一組,其他分為一組:

const $ = db.command.aggregate
db.collection('items').aggregate()
  .bucket({
    groupBy: '$price',
    boundaries: [0, 50, 100],
    default: 'other',
    output: {
      count: $.sum(1),
      ids: $.push('$_id')
    }
  })
  .end()

返回結果如下:

[
  {
    "_id": 0,
    "count": 2,
    "ids": [
      "1",
      "3"
    ]
  },
  {
    "_id": 50,
    "count": 2,
    "ids": [
      "2",
      "4"
    ]
  },
  {
    "_id": "other",
    "count": 22,
    "ids": [
      "5"
    ]
  }
]


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號