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

MongoDB中$group后如何获取关联的name字段并通过$project输出

解决MongoDB聚合$group后丢失name字段的问题

方法一:在$group阶段直接保留name字段

如果你的聚合源集合中本身包含name字段(且同一个id对应的name值唯一),可以直接在$group阶段添加对name字段的处理——使用$first或$last操作符提取分组内的name值(同一分组下的name一致,两者效果相同):

{
  '$group': {
    '_id': '$id',
    'name': {'$first': '$name'}, // 也可替换为$last
    'averageD': {'$avg': '$D'},
    'averageS': {'$avg': {'$first' : '$joinedS.score'} }  
  }
}

方法二:通过$lookup关联profiles集合获取name字段

如果name字段仅存在于独立的profiles集合中,需要结合$lookup完成关联匹配,再提取name字段,有两种实现顺序:

方案1:先聚合分组,再关联取name

适合源集合数据量较大的场景,先分组减少后续关联的数据量:

[
  {
    '$group': {
      '_id': '$id',
      'averageD': {'$avg': '$D'},
      'averageS': {'$avg': {'$first' : '$joinedS.score'} }  
    }
  },
  {
    '$lookup': {
      'from': 'profiles',
      'localField': '_id',
      'foreignField': 'id',
      'as': 'profileInfo'
    }
  },
  {
    '$addFields': {
      'name': {'$arrayElemAt': ['$profileInfo.name', 0]} // 取出匹配到的唯一name
    }
  },
  {
    '$project': {
      'profileInfo': 0 // 可选:移除临时关联数组字段
    }
  }
]

方案2:先关联,再聚合分组

适合源集合数据量较小的场景,关联后直接在分组阶段提取name:

[
  {
    '$lookup': {
      'from': 'profiles',
      'localField': 'id',
      'foreignField': 'id',
      'as': 'profileInfo'
    }
  },
  {
    '$addFields': {
      'name': {'$arrayElemAt': ['$profileInfo.name', 0]}
    }
  },
  {
    '$group': {
      '_id': '$id',
      'name': {'$first': '$name'},
      'averageD': {'$avg': '$D'},
      'averageS': {'$avg': {'$first' : '$joinedS.score'} }  
    }
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:05:18