【问题标题】:MongoDB - How to perform a $match inside $switch statementMongoDB - 如何在 $switch 语句中执行 $match
【发布时间】:2022-11-22 10:31:00
【问题描述】:

我想在聚合查询中的 $switch 内执行搜索。我想持有一个变量并根据前端传来的数据更改它。如果那个变量“通讯”我想执行搜索。简单的话,我可以描述如下,

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: {}
      }
    }
  }

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework nosql-aggregation


    【解决方案1】:

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

    并使用$regexMatch运算符,$regex运算符在聚合管道中不支持。

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

    Sample Mongo Playground

    【讨论】:

    • 感谢@Yong Shun 的回复,这对我来说很好,但是如果 com 是一个对象数组怎么办如何在对象数组中搜索名称 com:[{name:a,des:aaaa},{name:b,des: “aa”}]
    • 也许这符合您的要求:Demo
    • 再次非常感谢@Yong Shun。最后一个问题我想在 switch $match{ $or: [{ name: /"a"/ }, { com: /"a"/ }, { com: { $elemMatch: { 名称: /"a"/ } } }] }
    • 嗨,抱歉,我没有收到您关于最新评论的问题。如果您遇到任何问题,欢迎为其创建另一个问题,因为当前答案是为原始问题设计的。很难提供一个准确的如果您不断更改要求并且没有提供确切的信息/数据,请回答。当你写一个新问题时,这是一个善意的提醒。谢谢。
    • 嗨朋友@young Shun 我在这里添加我的问题,让你更清楚link
    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2011-07-18
    • 1970-01-01
    • 2014-03-27
    相关资源
    最近更新 更多