本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$bucket
8.0 版的新功能
Elastic 叢集不支援。
Amazon DocumentDB $bucket 中的彙總階段可讓您根據指定的表達式和儲存貯體邊界,將輸入文件分組至儲存貯體。這對於分析屬於特定值範圍或類別的資料非常有用。
參數
-
groupBy(必要):指定要分組之值的表達式。 -
boundaries(必要):定義儲存貯體邊界的雙值陣列。文件會根據落在指定邊界內的groupBy表達式值指派給儲存貯體。 -
default(選用):為groupBy表達式值未落在任何指定邊界的文件輸出的常值。 -
output(選用):指定要為每個儲存貯體輸出資訊的物件。您可以使用累積器運算子,例如$sum、$min、$avg和$max來計算每個儲存貯體的彙總。
範例 (MongoDB Shell)
下列範例示範如何使用 $bucket階段,依價格範圍將銷售資料分組。
建立範例文件
db.sales.insertMany([ { item: "abc", price: 10, quantity: 2, date: new Date("2020-09-01") }, { item: "def", price: 20, quantity: 1, date: new Date("2020-10-01") }, { item: "ghi", price: 5, quantity: 3, date: new Date("2020-11-01") }, { item: "jkl", price: 15, quantity: 2, date: new Date("2020-12-01") }, { item: "mno", price: 25, quantity: 1, date: new Date("2021-01-01") } ]);
查詢範例
db.sales.aggregate([ { $bucket: { groupBy: "$price", boundaries: [0, 10, 20, 30], default: "Other", output: { "count": { $sum: 1 }, "totalQuantity": { $sum: "$quantity" } } } }, { $sort: { _id: 1 } } ])
輸出
[
{ _id: 0, count: 1, totalQuantity: 3 },
{ _id: 10, count: 2, totalQuantity: 4 },
{ _id: 20, count: 2, totalQuantity: 2 }
]
程式碼範例
若要檢視使用 $bucket命令的程式碼範例,請選擇您要使用的語言標籤: