MongoDB-如何在$ switch语句中执行$匹配

发布于 2025-01-31 12:12:57 字数 631 浏览 3 评论 0原文

我想在聚合查询中执行$ switch内的搜索。我想容纳一个变量,并根据前端的数据进行更改。如果该变量“ com” 我想执行搜索。简而言之,我可以描述如下,

let search = "com"
if (search == "com") {
  $match{
     com: {$regex: "search_data"}}
}

这就是我尝试执行任务的方式:

  {
    $match: {
      $expr: {
        $switch: {
          branches: [
            {
              case: {
                $eq: ['$search', 'com']
              },
              then: {
                com: { $regex: "serch_data" }
              }
            },
         ],
         default: {}
      }
    }
  }

I want to perform a search inside a $switch in an aggregation query. I want to hold a variable and change it according to the data from the front end. if that variable "com" I want to perform a search. On simple words, I can describe it as follows,

let search = "com"
if (search == "com") {
  $match{
     com: {$regex: "search_data"}}
}

This is how I tried to perform the task:

  {
    $match: {
      $expr: {
        $switch: {
          branches: [
            {
              case: {
                $eq: ['$search', 'com']
              },
              then: {
                com: { $regex: "serch_data" }
              }
            },
         ],
         default: {}
      }
    }
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦过后 2025-02-07 12:12:57

您不应使用$ search,而应使用案例:{$ eq:['com',search]}$ search请参阅文档中的字段。

并使用$ REGEXMATCH操作员,$ REGEX操作员在聚合管道中不支持。

{
  $match: {
    $expr: {
      $switch: {
        branches: [
          {
            case: {
              $eq: [
                "com",
                search // search variable
                
              ]
            },
            then: {
              $regexMatch: {
                input: "$com",
                regex: "serch_data"
              }
            }
          },
          
        ],
        default: {}
      }
    }
  }
}

示例mongo playground

You should not use $search, but case: { $eq: ['com', search ] }. $search refer to field in document.

And use $regexMatch operator, $regex operator doesn't support in aggregation pipeline.

{
  $match: {
    $expr: {
      $switch: {
        branches: [
          {
            case: {
              $eq: [
                "com",
                search // search variable
                
              ]
            },
            then: {
              $regexMatch: {
                input: "$com",
                regex: "serch_data"
              }
            }
          },
          
        ],
        default: {}
      }
    }
  }
}

Sample Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文