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

如何在Mongo中统计多维数组元素并查询符合条件的讲师多字段信息

问题原因

你当前的聚合查询无法返回系名、薪资字段,是因为$group阶段仅设置了_id: "$name"和授课计数,没有保留讲师的其他属性,分组后就丢失了dept_name、salary字段的信息。

最优解决方案

因为你的需求是按授课条目数直接统计(同一门课教授多次计数多次),不需要拆分数组再分组聚合,直接用$size运算符获取teaches数组的长度即可,查询性能更高:

db.instructors.aggregate([
  // 第一步筛选:薪资>75000,且授课总数量为2
  {
    $match: {
      salary: { $gt: 75000 },
      $expr: { $eq: [ { $size: "$teaches" }, 2 ] }
    }
  },
  // 第二步返回指定字段
  {
    $project: {
      _id: 0,
      name: 1,
      dept_name: 1,
      salary: 1
    }
  }
])

原有写法的修复方案

如果后续需要对授课条目做额外过滤(比如只统计某一年的授课数),要保留$unwind+$group的结构,可以在分组阶段用$first保留同个讲师的固定属性:

db.instructors.aggregate([
  {
    $match: { salary: { $gt: 75000 } }
  },
  { $unwind: "$teaches" },
  {
    $group: {
      _id: "$name",
      // 保留同个讲师的系名、薪资
      dept_name: { $first: "$dept_name" },
      salary: { $first: "$salary" },
      totalCourses: { $sum: 1 }
    }
  },
  {
    $match: { totalCourses: 2 }
  },
  // 调整返回字段格式,去掉_id
  {
    $project: {
      _id: 0,
      name: "$_id",
      dept_name: 1,
      salary: 1
    }
  }
])

补充说明

你提供的示例数据中没有符合「薪资>75000且授课数为2」的记录:

  • 讲师A薪资68000不满足薪资条件
  • 讲师C薪资90000符合,但授课数为3
  • 讲师B薪资72000不满足薪资条件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 20:48:02