mongo按照商品的价格来 进行分类统计,想按照价格在 0~10 之间,10~20 之间,还有 20~30,30~40 以及大于 40 的,希 望能够统计每一个区间里面商品的个数
时间: 2023-07-18 13:47:59 浏览: 41
可以使用MongoDB的聚合框架来实现按照商品价格进行分类统计。以下是聚合管道的步骤:
1. 使用 $match 操作符过滤出价格在指定范围内的商品,例如:
```
{
$match: {
price: { $gte: 0, $lt: 10 }
}
}
```
2. 使用 $bucket 操作符创建区间并统计每个区间内的商品数量,例如:
```
{
$bucket: {
groupBy: "$price",
boundaries: [0, 10, 20, 30, 40],
default: "greater than or equal to 40",
output: {
count: { $sum: 1 }
}
}
}
```
这将会将价格在 0~10、10~20、20~30、30~40 和大于等于 40 的商品分别放入不同的桶中,并统计每个桶内商品的数量。
完整的聚合管道如下所示:
```
db.products.aggregate([
{
$match: {
price: { $gte: 0, $lt: 50 }
}
},
{
$bucket: {
groupBy: "$price",
boundaries: [0, 10, 20, 30, 40],
default: "greater than or equal to 40",
output: {
count: { $sum: 1 }
}
}
}
])
```
注意,上面的聚合管道假设商品的价格存储在 `price` 字段中,你需要根据实际情况修改聚合管道。