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

MongoDB聚合查询:筛选指定学年无健康记录的学生

解决MongoDB跨集合筛选无对应记录的问题

你可以通过MongoDB的聚合管道,结合$lookup和$match操作实现需求,具体查询语句如下:

db.students.aggregate([
  {
    $lookup: {
      from: "student_health_records",
      let: { studentId: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ["$stud_health_id", "$$studentId"] },
                { $eq: ["$schoolYear", ObjectId("sy234")] }
              ]
            }
          }
        }
      ],
      as: "health_records"
    }
  },
  {
    $match: {
      health_records: { $size: 0 }
    }
  }
])

步骤说明:

  1. $lookup 精准关联目标数据:

    • 从student_health_records集合中关联数据,通过let传递当前学生的_id到子管道。
    • 子管道的$match同时满足两个条件:健康记录的stud_health_id匹配学生_id,且schoolYear为指定的ObjectId('sy234'),只获取目标学年的关联记录,避免冗余数据。
  2. $match 筛选无对应记录的学生:

    • 通过$size: 0判断health_records数组为空,说明该学生在指定学年没有对应的健康记录,符合筛选要求。

执行该查询后,会返回学生集合中的第一条(_id: ObjectId('st_123'))和第三条(_id: ObjectId('st_345'))文档,与需求一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:15:48