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

MongoDB聚合查询中嵌套数组的$match匹配问题求助

MongoDB聚合查询解决方案

核心思路

要解决嵌套数组匹配失效的问题,需在$lookup关联options集合时,通过$expr引用外层的$$category_id变量,结合$in匹配关联产品的分类ID,确保筛选器选项能正确关联到指定分类。

完整聚合查询代码

db.categories.aggregate([
  {
    $match: {
      _id: ObjectId("60d21b4667d0d8992e610c85") // 可替换为任意查询条件,$$category_id会自动取当前文档的_id
    }
  },
  {
    $lookup: {
      from: "filters",
      localField: "_id",
      foreignField: "category_id",
      as: "filters"
    }
  },
  {
    $unwind: "$filters"
  },
  {
    $lookup: {
      from: "options",
      let: {
        category_id: "$_id",
        filter_id: "$filters._id"
      },
      pipeline: [
        {
          $lookup: {
            from: "products",
            localField: "product_ids",
            foreignField: "_id",
            as: "products"
          }
        },
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ["$filter_id", "$$filter_id"] },
                { $in: ["$$category_id", "$products.category_ids"] }
              ]
            }
          }
        },
        {
          $project: {
            _id: 1,
            name: 1,
            filter_id: 1
          }
        }
      ],
      as: "filters.options"
    }
  },
  {
    $group: {
      _id: "$_id",
      name: { $first: "$name" },
      filters: { $push: "$filters" }
    }
  }
])

关键步骤说明

  • 外层$match:指定目标分类,$$category_id会引用当前分类文档的_id,兼容任意查询条件。
  • 关联filters集合:通过category_id关联分类对应的筛选器。
  • 关联options集合的子管道:
    1. 先关联products集合,获取选项对应的产品信息。
    2. 使用$expr结合$in,检查产品的category_ids数组中是否包含$$category_id,确保选项属于当前分类。
    3. 投影需要的字段,精简返回结果。
  • 重新分组:将拆分的筛选器重新组合为数组,恢复原数据结构。

问题解决原理

之前匹配失效是因为外层$match无法穿透嵌套的products数组,而在options的子管道中,先关联products再用$expr引用$$category_id进行匹配,能精准筛选出属于指定分类的筛选器选项,避免返回空数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:40:08