Search code examples
mongodbmongodb-queryaggregation-frameworknosql-aggregation

MongoDB - How to perform a $match inside $switch statement


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

Solution

  • 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