本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$bucket
8.0 版的新增内容
弹性集群不支持。
Amazon DocumentDB 中的$bucket聚合阶段允许您根据指定的表达式和存储桶边界将输入文档分组到存储桶中。这对于分析属于特定值范围或类别的数据非常有用。
参数
-
groupBy(必填):指定分组依据的值的表达式。 -
boundaries(必填):定义存储桶边界的双精度值数组。根据位于指定边界内的groupBy表达式值将文档分配给存储桶。 -
default(可选):为groupBy表达式值不属于任何指定边界的文档输出的文字值。 -
output(可选):一个对象,它指定要为每个存储桶输出的信息。您可以使用诸如$sum、$avg$min、和之类的累加器运算符$max来计算每个存储桶的聚合。
示例(MongoDB 外壳)
以下示例演示如何使用$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命令的代码示例,请选择要使用的语言的选项卡: