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

MongoDB聚合查询中$lookup操作后$filter过滤失效问题求助

问题原因

config.user_info是数组类型,直接访问$$child.config.user_info.mapped_id会返回该数组下所有mapped_id组成的集合(如示例中为[1,3]),用$eq直接和数值1比较无法匹配,因此$filter返回空数组。同时部分commands记录没有config.user_info字段,直接访问也会导致匹配逻辑异常。

解决方法

有两种常用实现方案,推荐使用第二种,过滤逻辑下推到关联阶段性能更好:

方案1:修改现有$filter的匹配条件

调整$filter的判断逻辑,检查1是否存在于mapped_id数组中,同时兼容无user_info的场景:

gateway_model.aggregate([
  {
    $match: { group_id: "0" }
  },
  {
    $project: { _id: 0, mac_id: 1 }
  },
  {
    $lookup: {
      from: "commands",
      localField: "mac_id",
      foreignField: "mac_id",
      as: "childs"
    }
  },
  {
    $project: {
      mac_id: 1,
      childs: {
        $filter: {
          input: "$childs",
          as: "child",
          cond: {
            $in: [1, { $ifNull: ["$$child.config.user_info.mapped_id", []] }]
          }
        }
      }
    }
  }
])

方案2:过滤逻辑下推到$lookup阶段(推荐)

在关联commands集合时就直接完成条件过滤,不需要先查询所有关联记录再做二次过滤,执行效率更高:

gateway_model.aggregate([
  {
    $match: { group_id: "0" }
  },
  {
    $project: { _id: 0, mac_id: 1 }
  },
  {
    $lookup: {
      from: "commands",
      let: { cur_mac: "$mac_id" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$mac_id", "$$cur_mac"] },
            "config.user_info": { $elemMatch: { mapped_id: 1 } }
          }
        }
      ],
      as: "childs"
    }
  }
])

执行后mac_id=18001887的记录会返回符合条件的childs,mac_id=18001889的记录childs为空数组,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:54:05