如何在 Mongo 中执行 $match with $or inside $switch 语句

How to perform a $match with $or inside $switch statement in Mongo

您好,我正在尝试在 switch 中进行多次搜索,所以如果以下 user:search_data||com:search_data||fruit 之一,我想执行此操作: serch_data 匹配 return 个搜索结果。 我想做,

$match:{
          $or:[{ user:{$regex:"search_data"}},
          {com:{$regex:"search_data"}},
          {fruit:{$elemMatch: {name:{$regex:"search_data"}}}}
}

这是一个搜索,如果是用户,它应该搜索用户,如果是 com,它应该搜索公司,我现在可以做到这一点,如果搜索数据存在于用户 ORcomOR水果应该return搜索结果

   {
            $match: {
              $expr: {
                $switch: {
                  branches: [
                    {
                      case: {
                        $eq: ['$search', 'all']
                      },
                      then: {
                       
                       //to this
                      }
                    },
                 ],
                 default: {}
              }
            }
          }

示例数据

 user:"rithuwa",
  com:"abc",
  fruit:[{name:"mango",des:"aaaaa"},{name:"mango",des:"nnnn"}]

示例输入

search_data:"rit"---->since this is in user it should output the record
search_data:"mango"--->since it in the fruit.name it should output the record
search_data:"ab"---->since it in the com it should output the record
search_data:"me"---->since it not in user,com or fruit should not give search record  

查询

  • 如果类型是全部检查所有的正则表达式
  • 否则根据类型签入每个

*您在发送查询之前知道类型,因此您可以在应用程序代码上执行此切换案例,并有 4 个查询,因此根据类型发送其中一个(波纹管在服务器上执行此操作并且查询更大,你可以用 4 个更小的查询来完成)

Playmongo

aggregate(
[{"$set": {"searchData": "mango", "searchType": "tags"}},
 {"$match": 
   {"$expr": 
     {"$switch": 
       {"branches": 
         [{"case": {"$eq": ["$searchType", "all"]},
            "then": 
             {"$or": 
               [{"$regexMatch": {"input": "$name", "regex": "$searchData"}},
                 {"$regexMatch": {"input": "$company", "regex": "$searchData"}},
                 {"$reduce": 
                   {"input": "$tags",
                    "initialValue": false,
                    "in": 
                     {"$or": 
                       ["$$value",
                         {"$regexMatch": 
                           {"input": "$$this.name", "regex": "$searchData"}}]}}}]}},
           {"case": {"$eq": ["$searchType", "name"]},
            "then": 
             {"$regexMatch": {"input": "$name", "regex": "$searchData"}}},
           {"case": {"$eq": ["$searchType", "company"]},
            "then": 
             {"$regexMatch": {"input": "$company", "regex": "$searchData"}}},
           {"case": {"$eq": ["$searchType", "tags"]},
            "then": 
             {"$reduce": 
               {"input": "$tags",
                "initialValue": false,
                "in": 
                 {"$or": 
                   ["$$value",
                     {"$regexMatch": 
                       {"input": "$$this.name", "regex": "$searchData"}}]}}}}],
        "default": true}}}},
     {"$unset": ["searchData", "searchType"]}])