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

如何在MongoDB $lookup中使用正则匹配外键并筛选目标交易记录

在MongoDB的$lookup中使用通配符匹配外部键字段

需求说明

需要检索Transaction集合中,desc字段的子串未出现在Keyword集合中的所有记录。即如果Transaction.desc包含任意一个Keyword.desc的内容,则排除该记录;反之则保留。

完整聚合查询代码

db.transaction.aggregate([
  {
    $lookup: {
      from: "keyword",
      let: { transDesc: "$desc" }, // 将当前Transaction的desc传递到子管道
      pipeline: [
        {
          $match: {
            $expr: {
              // 检查Transaction的desc是否包含当前Keyword的desc
              $regexMatch: {
                input: "$$transDesc",
                regex: "$desc",
                options: "i" // 可选,忽略大小写,根据需求调整
              }
            }
          }
        }
      ],
      as: "matchedKeywords"
    }
  },
  {
    // 过滤出没有匹配到任何关键词的记录
    $match: { matchedKeywords: { $size: 0 } }
  },
  {
    // 可选:移除临时的matchedKeywords字段,只保留原文档内容
    $unset: "matchedKeywords"
  }
])

代码解析

  1. $lookup阶段

    • let:定义变量transDesc,引用当前Transaction文档的desc字段,在子管道中通过$$transDesc访问。
    • pipeline:子管道里用$match结合$expr,使用$regexMatch实现模糊匹配——检查Transaction.desc是否包含Keyword.desc的内容。options: "i"是可选的忽略大小写匹配,可根据实际需求删除。
  2. $match阶段
    通过$size: 0过滤出matchedKeywords数组为空的文档,这些就是desc不包含任何关键词的目标记录。

  3. $unset阶段(可选)
    移除查询过程中生成的临时字段matchedKeywords,让结果只保留原Transaction文档的结构。

示例执行结果

针对提供的示例数据,上述查询会返回以下记录:

{
  "_id": ObjectId("6480267ab9fe78e82131b738"),
  "date": ISODate("2020-06-23T00:00:00.000Z"),
  "desc": "abcdef"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:20:14