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

MongoDB按分组取最小值并统计每组数量的聚合查询写法

MongoDB聚合查询实现需求

你可以通过以下聚合查询语句得到预期结果:

db.ProdTable.aggregate([
  // 按分类分组,计算每组的最低价格
  {
    $group: {
      _id: "$PrdCategory",
      minPrice: { $min: "$PrdPrice" }
    }
  },
  // 关联原集合,筛选出该分类中价格等于最低价格的所有文档
  {
    $lookup: {
      from: "ProdTable",
      let: { category: "$_id", minPrice: "$minPrice" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ["$PrdCategory", "$$category"] },
                { $eq: ["$PrdPrice", "$$minPrice"] }
              ]
            }
          }
        }
      ],
      as: "matchingDocs"
    }
  },
  // 整理输出字段,统计符合条件的记录数
  {
    $project: {
      _id: 0,
      ProdCategory: "$_id",
      "min(PrdPrice)": "$minPrice",
      count: { $size: "$matchingDocs" }
    }
  }
])

各阶段说明:

  • $group阶段:以PrdCategory为分组键,计算每组的最低价格minPrice。
  • $lookup阶段:关联原集合,通过子管道筛选出当前分类下价格等于最低价格的所有文档,结果存入matchingDocs数组。
  • $project阶段:重新定义输出字段,移除默认的_id,将分组键重命名为ProdCategory,保留最低价格并命名为min(PrdPrice),用$size函数统计matchingDocs数组的长度,得到该最低价格对应的记录数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:31:02