新聞中心
Aggregate.bucket(object: Object): Aggregate
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
聚合階段。將輸入記錄根據(jù)給定的條件和邊界劃分成不同的組,每組即一個(gè) bucket。
參數(shù)
object: Object
返回值
Aggregate
API 說明
每組分別作為一個(gè)記錄輸出,包含一個(gè)以下界為值的 _id 字段和一個(gè)以組中記錄數(shù)為值的 count 字段。count 在沒有指定 output 的時(shí)候是默認(rèn)輸出的。
bucket 只會在組內(nèi)有至少一個(gè)記錄的時(shí)候輸出。
bucket 的形式如下:
bucket({
groupBy: ,
boundaries: [, , ...],
default: ,
output: {
: ,
...
:
}
})
groupBy 是一個(gè)用以決定分組的表達(dá)式,會應(yīng)用在各個(gè)輸入記錄上??梢杂?nbsp;$ 前綴加上要用以分組的字段路徑來作為表達(dá)式。除非用 default 指定了默認(rèn)值,否則每個(gè)記錄都需要包含指定的字段,且字段值必須在 boundaries 指定的范圍之內(nèi)。
boundaries 是一個(gè)數(shù)組,每個(gè)元素分別是每組的下界。必須至少指定兩個(gè)邊界值。數(shù)組值必須是同類型遞增的值。
default 可選,指定之后,沒有進(jìn)入任何分組的記錄將都進(jìn)入一個(gè)默認(rèn)分組,這個(gè)分組記錄的 _id 即由 default 決定。default 的值必須小于 boundaries 中的最小值或大于等于其中的最大值。default 的值可以與 boundaries 元素值類型不同。
output 可選,用以決定輸出記錄除了 _id 外還要包含哪些字段,各個(gè)字段的值必須用累加器表達(dá)式指定。當(dāng) output 指定時(shí),默認(rèn)的 count 是不會被默認(rèn)輸出的,必須手動指定:
output: {
count: $.sum(1),
...
:
}
使用 bucket 需要滿足以下至少一個(gè)條件,否則會拋出錯(cuò)誤:
- 每一個(gè)輸入記錄應(yīng)用 groupBy 表達(dá)式獲取的值都必須是一個(gè)在 boundaries 內(nèi)的值
- 指定一個(gè) default 值,該值在 boundaries 以外,或與 boundaries 元素的值不同的類型。
示例
假設(shè)集合 items 有如下記錄:
{
_id: "1",
price: 10
}
{
_id: "2",
price: 50
}
{
_id: "3",
price: 20
}
{
_id: "4",
price: 80
}
{
_id: "5",
price: 200
}
對上述記錄進(jìn)行分組,將 [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()
返回結(jié)果如下:
[
{
"_id": 0,
"count": 2,
"ids": [
"1",
"3"
]
},
{
"_id": 50,
"count": 2,
"ids": [
"2",
"4"
]
},
{
"_id": "other",
"count": 22,
"ids": [
"5"
]
}
]
分享題目:創(chuàng)新互聯(lián)小程序教程:SDK數(shù)據(jù)庫Aggregate·劃分輸入數(shù)據(jù)
轉(zhuǎn)載源于:http://www.5511xx.com/article/cccjdid.html


咨詢
建站咨詢

