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

如何在MongoDB集合的多维数组字段中投影指定元素?

MongoDB 获取嵌套数组中指定元素的方法

需求:从test集合的文档中,提取出phones数组里id为1的元素,输出格式为{'id':1, 'number':'000-000'}。

方法一:使用聚合管道(推荐)

通过$unwind展开嵌套数组,再筛选目标元素,最后提取结果:

db.test.aggregate([
  // 定位到目标文档
  { $match: { id: "stack" } },
  // 展开nums数组,将每个数组元素转为独立文档
  { $unwind: "$nums" },
  // 展开nums下的phones数组
  { $unwind: "$nums.phones" },
  // 筛选phones中id为1的元素
  { $match: { "nums.phones.id": 1 } },
  // 只保留目标phone字段,去掉_id
  { $project: { _id: 0, result: "$nums.phones" } }
])

执行后会得到类似结果:{ "result" : { "id" : 1, "number" : "000-000" } },如果需要直接获取对象,可在客户端处理或调整管道。

方法二:投影+客户端筛选

如果不想修改文档结构,先通过投影缩小范围,再在客户端提取目标元素:

db.test.find(
  { id: "stack" },
  { _id: 0, nums: 1 }
).forEach(doc => {
  // 合并所有phones数组并找到目标元素
  const targetPhone = doc.nums.flatMap(item => item.phones).find(phone => phone.id === 1);
  printjson(targetPhone);
})

这种方法适合数据量不大的场景,直接在Mongo Shell里就能输出目标对象。

方法三:聚合管道内用数组操作符(无需展开)

利用$reduce合并所有phones数组,再通过$arrayElemAt定位目标元素:

db.test.aggregate([
  { $match: { id: "stack" } },
  {
    $project: {
      _id: 0,
      targetPhone: {
        $arrayElemAt: [
          // 合并nums下所有phones数组
          { $reduce: { input: "$nums", initialValue: [], in: { $concatArrays: ["$$value", "$$this.phones"] } } },
          // 找到id为1的元素的索引
          { $indexOfArray: [
              { $reduce: { input: "$nums", initialValue: [], in: { $concatArrays: ["$$value", "$$this.phones.id"] } } },
              1
            ]
          }
        ]
      }
    }
  }
])

这种方法全程在数据库端处理,适合需要直接返回目标元素的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:02:09