💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
mongo聚合查询之 $bucket的作用: 大致说明:分段统计表的数据 ``` { $bucket: { groupBy: <expression>, // 需要统计的信息 可以是表达式或者字段 boundaries: [ <lowerbound1>, <lowerbound2>, ... ], // 约束信息的范围 default: <literal>, // 不在约束范围内的默认值 output: { //输出的字段信息 <output1>: { <$accumulator expression> }, ... <outputN>: { <$accumulator expression> } } } } ``` 数据 ~~~ { "_id" : 1, "title" : "title1", "year" : 1926, "price" : NumberDecimal("199.99") } { "_id" : 2, "title" : "title2", "year" : 1902, "price" : NumberDecimal("280.00") } { "_id" : 3, "title" : "title3", "year" : 1925, "price" : NumberDecimal("76.04") } { "_id" : 4, "title" : "title4", "price" : NumberDecimal("167.30") } { "_id" : 5, "title" : "title5 "price" : NumberDecimal("483.00") } { "_id" : 6, "title" : "title6" : 1913, "price" : NumberDecimal("385.00") } { "_id" : 7, "title" : "title7", "year" : 1893} { "_id" : 8, "title" : "title8", "year" : 1918, "price" : NumberDecimal("118.42") } ~~~ 执行查询: ~~~ db.artwork.aggregate( [ { $bucket: { groupBy: "$price", // 对prices字段进行统计查询 boundaries: [ 0, 200, 400 ], // 数据的边界范围,包左不包右 default: "Other", // 不在boundaries内的默认名称 output: { "count": { $sum: 1 }, // 统计 "titles" : { $push: "$title" } // 将改范围内的title组成数组 } } } ] ) ~~~ 结果: ~~~ { "_id" : 0, "count" : 4, "titles" : ["title1","title3","title4","title8"] }// 0<=prices<200 { "_id" : 200, "count" : 2, "titles" : [ "title2", "title6" ] }// 200<=prices<400 { "_id" : "Other", "count" : 2, "titles" : [ "title5", "title7" ] }// 不在0-400范围内的 ~~~