如何在Mongo中与$匹配或$ switch语句进行$匹配
嗨,我正在尝试在开关内部进行多个搜索,所以如果以下用户之一:search_data || com:search_data ||水果: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
Hi I am trying to get multiple searches inside switch so i want to do if one of the following user:search_data||com:search_data||fruit:serch_data matches return search results.
i want to do,
$match:{
$or:[{ user:{$regex:"search_data"}},
{com:{$regex:"search_data"}},
{fruit:{$elemMatch: {name:{$regex:"search_data"}}}}
}
this is a search if user it should search user, if com it should search company I have able to do that now i want when we gives all if search data exits on user OR Com OR fruit it should return the search results
{
$match: {
$expr: {
$switch: {
branches: [
{
case: {
$eq: ['$search', 'all']
},
then: {
//to this
}
},
],
default: {}
}
}
}
sample data
user:"rithuwa",
com:"abc",
fruit:[{name:"mango",des:"aaaaa"},{name:"mango",des:"nnnn"}]
sample input
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查询
*在发送查询之前先知道类型其中一个(Bellow在服务器上这样做,并且查询更大,您可以使用4个较小的查询来完成)
Playmongo
Query
*you know the type before sending the query, so you can do this switch case on application code, and have 4 queries, so based on the type to send one of them (the bellow does this on the server and query is bigger, you can do it with 4 much smaller queries)
Playmongo