如何在外键字段上使用通配符执行$查找?

任务是检索Keyword集合中desc子字符串为notTransaction中的所有记录.

desc in交易可以采用ABC<关键字&>定义的形式,并交叉引用到Keyword集合,如果找到,这应该是匹配的.

我想使用正则表达式.*XXX.*的负匹配来完成任务.

不确定如何在$查找中放置正则表达式子句.

Transaction个Collection :

transactions=[
{
  "_id": {
    "$oid": "6480267ab9fe78e82131b737"
  },
  "date": {
    "$date": "2020-06-22T00:00:00.000Z"
  },
  "desc": "abcKey1def",
},
{
  "_id": {
    "$oid": "6480267ab9fe78e82131b738"
  },
  "date": {
    "$date": "2020-06-23T00:00:00.000Z"
  },
  "desc": "abcdef",
}
]

Keyword个Collection :

keyword=[
{
  "_id": {
    "$oid": "64816f3828372d84a93cd4ad"
  },
  "code": 123,
  "desc": "Key1"
},
{
  "_id": {
    "$oid": "648174bf28372d84a93cd4b5"
  },
  "code": 456,
  "desc": "Key2",
}
]

我知道我可能需要用letpipeline...但不确定如何将它们组合在一起.

$lookup:{
  from: "keyword",
  let: {
    desc:'$desc'
  },
  pipeline: [
     ....?
  ]
  
  as: "result"
}

推荐答案

一种方法是在$lookup中使用$regexMatch.就像这样:

db.transactions.aggregate([
  {
    "$lookup": {
      "from": "keyword",
      "let": {
        desc: "$desc"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              "$regexMatch": {
                "input": "$$desc",
                "regex": {
                  "$concat": [
                    ".*",
                    "$desc",
                    ".*"
                  ]
                }
              }
            }
          }
        }
      ],
      "as": "matchingDocs"
    }
  },
  {
    "$match": {
      matchingDocs: []
    }
  }
])

Playground link.

Mongodb相关问答推荐

MongoDB聚合匹配字符串字符

映射数组值并查找每个匹配的集合

数组字段包含其他字段的数组值

MongoDB $lookup 查找字段值数组

使用Go的Mongo驱动程序,从MongoDB文档中获取元素并更新其值需要帮助

如何使用 MindsDB 和 MQL(对于我的 MongoDB 实例)实施零样本分类?

如何更新mongo中列表最后一个对象的属性

DB.collection('comments').find() 不工作

通过insertId MongoDB获取文档

根据条件删除一些数组元素并将数组的大小更新为mongo中的另一个文件

在数据中只有月份和年份的 mongodb 中字符串的日期时间

解析命令行时出错:unrecognized option --rest

将 MongoDB 地理空间索引与 3d 数据结合使用

如何在 MongoDb 中进行类似于嵌套 Sql Select 查询的嵌套查询

GeoJSON 和 MongoDB:将点存储为 GeoJSON.Point 是否值得?

为什么不建议在 MongoDB 中使用服务器端存储函数?

无法从 MongoDb C# 中的 BsonType ObjectId 反序列化字符串

mongodb nodejs - 转换圆形 struct

Mongoose.pre('save') 不会触发

从 Grunt 任务中启动 MongoDB