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

如何在MongoDB中带条件使用$project筛选嵌套子数组元素

你可以使用MongoDB聚合管道实现需求,以下是可直接运行的查询语句:

方案1:每个文档仅返回第一个匹配的子元素(匹配你给出的示例输出)

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      matchedItem: {
        $first: {
          $filter: {
            input: "$b",
            cond: { $eq: ["$$this.a", "$a"] }
          }
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$matchedItem"
    }
  }
])

方案2:返回所有符合条件的子元素

如果第一个文档中多个b数组元素的a值都和顶层a值相等,需要全部返回的话使用以下语句:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      matchedItems: {
        $filter: {
          input: "$b",
          cond: { $eq: ["$$this.a", "$a"] }
        }
      }
    }
  },
  { $unwind: "$matchedItems" },
  {
    $replaceRoot: {
      newRoot: "$matchedItems"
    }
  }
])

步骤说明

  1. $filter 遍历b数组,$$this指向数组当前遍历元素,判断子元素的a值是否和顶层文档的a值相等,过滤出所有符合条件的子元素。
  2. $first 取过滤结果的第一个元素,适配你给出的示例输出,不需要可以删除。
  3. $unwind 将过滤后的数组拆分为单个文档。
  4. $replaceRoot 将匹配到的子元素提升为最终返回的顶层文档,去掉多余的字段。

如果你使用的是MongoDB 4.2及以上版本,$replaceRoot可以替换为等价的$replaceWith: "$matchedItem"写法,语法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:18:02