MongoDB-如何在$ switch语句中执行$匹配
我想在聚合查询中执行$ 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: {}
}
}
}
I want to perform a search inside a $switch
in an aggregation query. I want to hold a variable and change it according to the data from the 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: {}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应使用
$ search
,而应使用案例:{$ eq:['com',search]}
。$ search
请参阅文档中的字段。并使用
$ REGEXMATCH
操作员,$ REGEX
操作员在聚合管道中不支持。示例mongo playground
You should not use
$search
, butcase: { $eq: ['com', search ] }
.$search
refer to field in document.And use
$regexMatch
operator,$regex
operator doesn't support in aggregation pipeline.Sample Mongo Playground