如何在Mongo中与$或$switch语句内执行$match



嗨,我正试图获得多个搜索开关内,所以我想做,如果以下一个用户:search_data||com:search_data||fruit:serch_data匹配返回搜索结果。我想做的,

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

这是一个搜索如果用户它应该搜索用户,如果com它应该搜索公司我现在能够做到这一点,我想当我们给出所有的如果搜索数据存在于用户com水果时它应该返回搜索结果

{
$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  
查询
  • 如果type是all,检查all
  • 中的正则表达式

*在发送查询之前你知道类型,所以你可以在应用程序代码上做这个开关,并且有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"]}])

相关内容

  • 没有找到相关文章

最新更新