Home > Software engineering >  How to perform a $match inside $switch statement in mongo
How to perform a $match inside $switch statement in mongo

Time:05-23

I want perform a search inside a $switch in a aggregation Query. I want to hold a variable and change it according to the data from 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: {}
      }
    }
  }

CodePudding user response:

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

  • Related