demo_10_02 云数据库聚合_bucket_01
// 1. 数据库数据
// {
// "items": { // 集合(表名)
// "data": [ // 数据
// {
// "_id": 1,
// "price": 10
// },
// {
// "_id": 2,
// "price": 50
// },
// {
// "_id": 3,
// "price": 20
// },
// {
// "_id": 4,
// "price": 80
// },
// {
// "_id": 5,
// "price": 200
// }
// ]
// }
// }
// 02. 聚合操作
'use strict';
const db = uniCloud.database();
const $ = db.command.aggregate;
exports.main = async(event, context) => {
// 对上述记录进行分组,将 [0, 50) 分为一组,[50, 100) 分为一组,其他分为一组:
let res = await db.collection('items').aggregate()
.bucket({
groupBy: '$price',
boundaries: [0, 50, 100],
default: 'other',
output: {
// 输出两个字段的值
count: $.sum('$price'), // 同组 price 值相加
ids: $.push('$_id') // push 表示输出为数组
}
})
.end();
return res;
};
// 聚合之后的返回值
// {
// "affectedDocs": 3,
// "data": [{
// "_id": 0,
// "count": 30,
// "ids": [1, 3]
// }, {
// "_id": 50,
// "count": 130,
// "ids": [2, 4]
// }, {
// "_id": "other",
// "count": 200,
// "ids": [5]
// }]
// }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步