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

MongoDB如何按confrontationId分组matches对象并输出预期格式结果

MongoDB分组查询实现方案

你可以通过MongoDB聚合管道实现需求,完整查询语句如下:

db.你的集合名.aggregate([
  // 展开matches数组,将单场比赛转为独立文档
  { $unwind: "$rounds.matches" },
  // 按confrontationId分组,归集同组的所有比赛对象
  {
    $group: {
      _id: "$rounds.matches.confrontationId",
      matchList: { $push: "$rounds.matches" }
    }
  },
  // 把所有分组数组归集为一个总数组
  {
    $group: {
      _id: null,
      finalResult: { $push: "$matchList" }
    }
  },
  // 输出结果直接为总数组,匹配预期格式
  { $replaceRoot: { newRoot: "$finalResult" } }
])

各阶段作用说明

  • $unwind:将嵌套的rounds.matches数组拆分,每场比赛生成一条独立文档,为后续分组做准备
  • 第一个$group:以confrontationId作为分组键,将同组的所有比赛对象存入matchList数组
  • 第二个$group:不设置分组规则,将上一步生成的所有分组数组合并为一个总数组
  • $replaceRoot:将最终结果数组直接作为输出根节点,完全符合你要求的输出格式

内容的提问来源于stack exchange,提问作者Daywison Ferreira Leal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:45:03