我想在聚合查詢中的$switch內執行搜索。我想保存一個變數并根據前端的資料進行更改。如果那個變數“com”我想執行搜索。用簡單的話我可以描述如下,
let search="com"
if(search=="com") {
$match{
com: {$regex: "search_data"}}
}
這就是我嘗試執行任務的方式:
{
$match: {
$expr: {
$switch: {
branches: [
{
case: {
$eq: ['$search', 'com']
},
then: {
com: { $regex: "serch_data" }
}
},
],
default: {}
}
}
}
uj5u.com熱心網友回復:
你不應該使用$search,但是case: { $eq: ['com', search ] }。$search請參閱檔案中的欄位。
并且使用$regexMatch運算子,$regex聚合管道中不支持運算子。
{
$match: {
$expr: {
$switch: {
branches: [
{
case: {
$eq: [
"com",
search // search variable
]
},
then: {
$regexMatch: {
input: "$com",
regex: "serch_data"
}
}
},
],
default: {}
}
}
}
}
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479381.html
標籤:mongodb mongodb查询 聚合框架 nosql-聚合
上一篇:MongoDB-分組并找到前N個
