• 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]
    //  }]
    // }
  • 相关阅读:
    广域网(ppp协议、HDLC协议)
    0120. Triangle (M)
    0589. N-ary Tree Preorder Traversal (E)
    0377. Combination Sum IV (M)
    1074. Number of Submatrices That Sum to Target (H)
    1209. Remove All Adjacent Duplicates in String II (M)
    0509. Fibonacci Number (E)
    0086. Partition List (M)
    0667. Beautiful Arrangement II (M)
    1302. Deepest Leaves Sum (M)
  • 原文地址:https://www.cnblogs.com/luwei0915/p/13385401.html
Copyright © 2020-2023  润新知