• demo_10_04 云数据库聚合_group_01


    // 1. 数据库数据
    // {
    //  "avatar": { // 集合(表名)
    //      "data": [ // 数据
    //          {
    //            "_id": "1",
    //            "alias": "john",
    //            "region": "asia",
    //            "scores": [40, 20, 80],
    //            "coins": 100
    //          },
    //          {
    //            "_id": "2",
    //            "alias": "arthur",
    //            "region": "europe",
    //            "scores": [60, 90],
    //            "coins": 20
    //          },
    //          {
    //            "_id": "3",
    //            "alias": "george",
    //            "region": "europe",
    //            "scores": [50, 70, 90],
    //            "coins": 50
    //          },
    //          {
    //            "_id": "4",
    //            "alias": "john",
    //            "region": "asia",
    //            "scores": [30, 60, 100, 90],
    //            "coins": 40
    //          },
    //          {
    //            "_id": "5",
    //            "alias": "george",
    //            "region": "europe",
    //            "scores": [20],
    //            "coins": 60
    //          },
    //          {
    //            "_id": "6",
    //            "alias": "john",
    //            "region": "asia",
    //            "scores": [40, 80, 70],
    //            "coins": 120
    //          }
    //      ]
    //  }
    // }

    // 02. 聚合操作 group
    // 聚合阶段,将输入记录按给定表达式分组,输出时每个记录代表一个分组,每个记录的 _id 是区分不同组的 key。
    // 输出记录中也可以包括累计值,将输出字段设为累计值即会从该分组中计算累计值。
    'use strict';
    const db = uniCloud.database();
    const $ = db.command.aggregate;
    exports.main = async(event, context) => {
        let res = await db.collection('avatar').aggregate()
            // 按字段值分组
            .group({
                // 根据_id分组
                _id: '$alias',
                // 统计 alias值出现的次数,1表示*1输出,如果是2,表示 次数*2 输出
                num: $.sum(1)
            })
            .end();
        return res;
    };

    // 聚合之后的返回值
    // {
    //  "affectedDocs": 3,
    //  "data": [{
    //          "_id": "george",
    //          "num": 2
    //      },
    //      {
    //          "_id": "arthur",
    //          "num": 1
    //      },
    //      {
    //          "_id": "john",
    //          "num": 3
    //      }
    //  ]
    // }
  • 相关阅读:
    MIT6.S081 Lab traps
    MIT6.S081 Preparation: Read chapter 7
    MIT6.S081 Lab cow
    MIT6.S081 Lab Multithreading
    MIT6.S081 Preparation: Read chapter 5
    MIT6.S081 Lab networking
    java接口代码中出现$ref
    java获取encodeURI编码后的链接
    剑指 Offer II 002. 二进制加法 模拟法
    Leetcode NO.46 Permutations 全排列
  • 原文地址:https://www.cnblogs.com/luwei0915/p/13386651.html
Copyright © 2020-2023  润新知