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

MongoDB聚合查询:合并电影数量最少的年份为数组

MongoDB聚合实现:找出电影数量最少的年份(支持多年份合并)

以下是满足需求的聚合管道代码,直接运行即可得到指定格式的结果:

db.movies.aggregate([
  // 1. 按年份分组,统计每个年份的电影数量
  {
    $group: {
      _id: "$year",
      movies: { $sum: 1 }
    }
  },
  // 2. 按电影数量升序排序,最小值排在最前
  {
    $sort: { movies: 1 }
  },
  // 3. 将所有年份统计结果合并为一个数组
  {
    $group: {
      _id: null,
      yearCounts: { $push: { year: "$_id", count: "$movies" } }
    }
  },
  // 4. 计算出所有年份中最少的电影数量
  {
    $addFields: {
      minCount: { $min: "$yearCounts.count" }
    }
  },
  // 5. 筛选出数量等于最小值的年份,组成数组
  {
    $addFields: {
      minYears: {
        $map: {
          input: { $filter: {
            input: "$yearCounts",
            cond: { $eq: ["$$this.count", "$minCount"] }
          } },
          as: "item",
          in: "$$item.year"
        }
      }
    }
  },
  // 6. 调整输出为指定格式
  {
    $project: {
      _id: "$minYears",
      movies: "$minCount",
      yearCounts: 0,
      minCount: 0
    }
  }
])

步骤解释:

  • $group(第一步):将同一年份的电影归为一组,用$sum:1统计每组的文档数量(即该年份的电影数)。
  • $sort:按电影数量从小到大排序,确保后续能快速定位最小数量的年份。
  • $group(第二步):把所有年份的统计结果打包成一个数组,避免分散成多个文档,方便后续统一筛选。
  • $addFields(计算minCount):从统计数组中提取所有电影数量,用$min得到最小值。
  • $addFields(筛选minYears):先用$filter保留数组中数量等于最小值的条目,再用$map提取这些条目的年份,组成最终的年份数组。
  • $project:清理输出字段,只保留要求的_id(年份数组)和movies(最小数量),去掉中间过程的冗余字段。

运行后会输出符合要求的格式,例如:

{ "_id": [2001, 2005], "movies": 3 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:56:01