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

如何在MongoDB中提取内嵌数组里指定类型元素的名称?

MongoDB 查询内嵌数组指定元素的name字段值

假设你的集合中文档结构如下(与你的jq示例对应):

{
  "_id": ObjectId("1234567890abcdef12345678"),
  "elements": [
    {"name": "element1", "type": "normal"},
    {"name": "element2", "type": "important"},
    {"name": "element3", "type": "normal"},
    {"name": "element4", "type": "important"}
  ]
}

方法1:$filter+$project分阶段聚合

先筛选出符合条件的数组元素,再提取目标字段,逻辑清晰:

db.collection.aggregate([
  // 筛选出type为important的elements元素
  {
    $project: {
      filteredElements: {
        $filter: {
          input: "$elements",
          as: "elem",
          cond: { $eq: ["$$elem.type", "important"] }
        }
      },
      _id: 0
    }
  },
  // 提取筛选后元素的name字段
  {
    $project: {
      importantNames: "$filteredElements.name"
    }
  }
])

执行结果:

{ "importantNames": ["element2", "element4"] }

方法2:$filter+$map一步聚合

将筛选和字段提取合并到一个阶段,写法更简洁:

db.collection.aggregate([
  {
    $project: {
      importantNames: {
        $map: {
          input: {
            $filter: {
              input: "$elements",
              as: "elem",
              cond: { $eq: ["$$elem.type", "important"] }
            }
          },
          as: "item",
          in: "$$item.name"
        }
      },
      _id: 0
    }
  }
])

执行结果与方法1完全一致。

注意事项

  • 用find配合$elemMatch只能返回数组中第一个匹配type: "important"的元素,无法获取所有符合条件的元素,因此必须通过聚合管道实现需求。
  • 上述方法支持处理集合中的多条文档,每条文档会返回对应的importantNames数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:05:19