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

MongoDB遍历嵌套map结构及查询包含指定学生的学校的方法

MongoDB动态key学生数据查询&遍历方案

一、查询所有包含学生John的学校

你可以使用MongoDB聚合管道的$objectToArray运算符,将动态key的school.students对象转换为键值对数组后匹配取值,查询语句如下:

db.你的集合名.aggregate([
  // 新增临时字段,将students对象转换为[{k: "学生id", v: "学生姓名"}]格式的数组
  {
    $addFields: {
      studentTempArr: { $objectToArray: "$school.students" }
    }
  },
  // 匹配数组中存在姓名为John的记录
  {
    $match: {
      "studentTempArr.v": "John"
    }
  },
  // 可选:删除临时字段,返回原始文档结构
  {
    $unset: "studentTempArr"
  }
])

二、遍历动态key的students对象

school.students是普通对象而非数组,本身不支持forEach方法,你可以在应用层按以下两种方式遍历:

// 假设doc为查询返回的单条文档对象
const students = doc.school.students

// 方式1:for in遍历key
for (const stuId in students) {
  const stuName = students[stuId]
  // 自定义处理逻辑
  console.log(`学生ID:${stuId},姓名:${stuName}`)
}

// 方式2:转为数组后遍历
Object.entries(students).forEach(([stuId, stuName]) => {
  // 自定义处理逻辑
  console.log(`学生ID:${stuId},姓名:${stuName}`)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:54:02