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]
//  }]
// }
原文地址:https://www.cnblogs.com/luwei0915/p/13385401.html