You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MongoDB Aggregation按车型分组统计各颜色去重计数

解决方案

首先要注意你的原始数据中car_type字段存在首尾多余空格,会导致同类型车型被识别为不同分组,聚合时需要先做清洗。你可以直接使用以下聚合查询实现需求:

db.collection.aggregate([
  // 第一步:清洗car_type字段的首尾空格,若正式数据无空格可删除本阶段
  {
    $addFields: {
      cleaned_car_type: { $trim: { input: "$car_type" } }
    }
  },
  // 第二步:按清洗后的车型+颜色双维度分组,统计每个颜色的数量
  {
    $group: {
      _id: {
        car_type: "$cleaned_car_type",
        color: "$color"
      },
      count: { $sum: 1 }
    }
  },
  // 第三步:按车型单维度分组,将同车型的所有颜色和数量聚合为数组
  {
    $group: {
      _id: "$_id.car_type",
      color_counts: {
        $push: {
          k: "$_id.color",
          v: "$count"
        }
      }
    }
  },
  // 第四步:将数组转为键值对,拼接为你需要的输出结构
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          { car_type: "$_id" },
          { $arrayToObject: "$color_counts" }
        ]
      }
    }
  }
])

返回结果示例

{
  "car_type": "suv",
  "red": 2,
  "blue": 2
},
{
  "car_type": "wagon",
  "red": 3
}

内容的提问来源于stack exchange,提问作者SpawN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:15:01