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

如何在MongoDB中查询数组内匹配指定字段的父级元素

方案1:使用find + $elemMatch投影(仅返回第一个匹配的子文档)

如果你只需要获取第一个匹配studentName: "ABC"的子元素,直接用查询+投影即可:

db.yourCollectionName.find(
  // 查询条件:匹配包含对应学生的父文档
  { "students.studentName": "ABC" },
  // 投影配置:仅返回数组中匹配的元素,隐藏默认返回的_id
  { 
    students: { $elemMatch: { studentName: "ABC" } },
    _id: 0 
  }
)

注意:该方案仅返回数组中第一个符合条件的子元素,若存在多个同名学生的场景不适用。


方案2:使用聚合管道$filter(返回所有匹配的子文档)

如果需要返回所有符合条件的子元素,或者需要对结果做二次处理,用聚合管道实现:

db.yourCollectionName.aggregate([
  // 第一步:先过滤出存在对应学生的父文档,减少后续计算量(可选但推荐添加)
  { $match: { "students.studentName": "ABC" } },
  // 第二步:过滤students数组,仅保留匹配的元素
  {
    $project: {
      _id: 0,
      students: {
        $filter: {
          input: "$students", // 要过滤的源数组
          as: "stu", // 遍历数组时的临时变量名
          cond: { $eq: [ "$$stu.studentName", "ABC" ] } // 匹配条件
        }
      }
    }
  },
  // 可选步骤:如果确定只有1个匹配结果,想直接返回对象而非数组,可以加这一步
  {
    $project: {
      matchedStudent: { $arrayElemAt: [ "$students", 0 ] }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:45:03