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

MongoDB中如何在$lookup关联集合后执行$match筛选子文档

你当前的聚合语句存在两个问题:

  1. $match: {"services.status": true} 仅会筛选出「关联结果中至少存在1个status为true的服务」的分类,不会把services数组中status为false的条目剔除,所以你得到的结果里services数组会包含status为false的service d。
  2. 没有过滤掉无符合条件服务的分类(比如示例中的WOMEN分类)。

方案1:使用带pipeline的$lookup(推荐,性能更优)

关联服务集合时直接完成过滤,避免关联无效数据,适合数据量较大的场景:

db.category.aggregate([
  // 可选:如果需要仅查询本身状态为true的分类,可以保留这一阶段
  {
    $match: {
      status: true
    }
  },
  {
    $lookup: {
      from: "services",
      let: { categoryId: "$id" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$category_id", "$$categoryId"] },
            status: true
          }
        }
      ],
      as: "services"
    }
  },
  // 过滤掉没有符合条件服务的分类
  {
    $match: {
      "services.0": { $exists: true }
    }
  }
])

方案2:关联后过滤数组

如果不想修改原有$lookup的写法,可以在关联后通过$filter过滤services数组:

db.category.aggregate([
  {
    "$lookup": {
      "from": "services",
      "localField": "id",
      "foreignField": "category_id",
      "as": "services"
    }
  },
  {
    $project: {
      id: 1,
      name: 1,
      status: 1,
      services: {
        $filter: {
          input: "$services",
          cond: { $eq: ["$$this.status", true] }
        }
      }
    }
  },
  // 过滤掉没有符合条件服务的分类
  {
    $match: {
      "services.0": { $exists: true }
    }
  }
])

两种方案都可以得到你要求的预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:18:00