嗨,我正在嘗試在 switch 內進行多個搜索,所以如果以下用戶之一: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
uj5u.com熱心網友回復:
詢問
- 如果型別是全部檢查所有的正則運算式
- 否則根據型別檢查每個
*您在發送查詢之前知道型別,因此您可以在應用程式代碼上執行此切換案例,并且有 4 個查詢,因此根據型別發送其中一個(波紋管在服務器上執行此操作并且查詢更大,您可以用 4 個小得多的查詢來完成)
玩蒙哥
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"]}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479378.html
標籤:mongodb 聚合框架 弹簧数据-MongoDB nosql-聚合
上一篇:使用R中Cowplot包中的plot_grid()將hist()和boxplot()物件轉換為ggplot()物件以對齊我的圖
