首页 > 解决方案 > 组合组累加器运算符

问题描述

我有一些 Mongo 代码可以按我想要的方式工作,但现在我正在尝试优化它!

我目前的实现有点冗长,我觉得有一些方法可以用来尽量减少为每个指标写出avg, min,变量...也许将它们组合在一起?max

为简单起见,我缩短了代码,但您可以看到它如何在大数据集上快速重复!

我当前的代码

db.player_data_2020.aggregate([
    {"$group": {
        "_id": null,
        "height_avg": {
            "$avg": "$PLAYER_HEIGHT"
        },
        "height_min": {
            "$min": "$PLAYER_HEIGHT"
        },
        "height_max": {
            "$max": "$PLAYER_HEIGHT"
        },

        "age_avg": {
            "$avg": "$PLAYER_AGE"
        },
        "age_min": {
            "$min": "$PLAYER AGE"
        },
        "age_max": {
            "$max": "$PLAYER_AGE"
        },

        "gamesPlayed_avg": {
            "$avg": "$GAMES_PLAYED"
        },
        "gamesPlayed_min": {
            "$min": "$GAMES_PLAYED"
        },
        "gamesPlayed_max": {
            "$max": "$GAMES_PLAYED"
        }
    }},
    {"$set": {
    "array": [
        {
          "Metric": "Height",
          "Avg": "$height_avg",
          "Min": "$height_min",
          "Max": "$height_max", 
          "Unit": "Feet"
        },
        {
          "Metric": "Age",
          "Avg": "$age_avg",
          "Min": "$age_min",
          "Max": "$age_max", 
          "Unit": "Years"
        },
        {
          "Metric": "Games Played",
          "Avg": "$gamesPlayed_avg",
          "Min": "$gamesPlayed_min",
          "Max": "$gamesPlayed_max", 
          "Unit": "per season"
        }
      ]
  }},
  {"$unwind": {
    "path": "$array"
  }},
  {"$replaceRoot": {
    "newRoot": "$array"
  }}
]);

我当前/期望的结果

[
  {
    "Metric": "Height",
    "Avg": 498105.628742515,
    "Min": 420620,
    "Max": 597838,
    "Unit": "Feet"
  },
  {
    "Metric": "Age",
    "Avg": 23.4,
    "Min": 18,
    "Max": 39,
    "Unit": "Years"
  },
  {
    "Metric": "Games Played",
    "Avg": 49.34,
    "Min": 0,
    "Max": 72,
    "Unit": "per season"
  }
]

标签: mongodbaggregation-framework

解决方案


推荐阅读