【问题标题】:How to check if string value of a field is a substring of another field in MongoDB如何检查一个字段的字符串值是否是MongoDB中另一个字段的子字符串
【发布时间】:2021-11-06 13:11:09
【问题描述】:

1.假设我有一个名为 test 的集合并包含三个文档。文档的结构如下:

{
       Text: " String is string",
       Text1:  "string"
       
       
 },

{
       Text: "Good is good",
       Text1: "good"
       
       
 } 
  1. 如何编写聚合查询来查找 Text 包含 Text1(不区分大小写)的所有文档?

【问题讨论】:

  • 这是无效的 JSON - 你的双引号有一个未完成的闭包。另外,什么是Text1?您为一个值显示一个字符串,但它不在双引号中。
  • 我正在使用手机输入 JSON。这就是我无法正确输入的原因
  • 我更新了 JSON 文件

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以使用正则表达式来匹配文本示例代码中的 text1: https://mongoplayground.net/p/d2WJO7sG1jO

    db.collection.aggregate([
  {
    $addFields: {
      matched: {
        $regexMatch: {
          "input": "$Text",
          "regex": "$Text1",
          options: "i"
        }
      }
    }
  },
  {
    "$match": {
      matched: true
    }
  },
  {
    "$project": {
      matched: 0
    }
  }
])

这里我们通过检查 Text1 是否存在于不区分大小写的 Text 中来添加额外的字段。如果找到匹配,那么只有我们返回匹配的结果。请注意,这里我们只检查未在文档中匹配的 self 文档。

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2022-07-01
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多