我正在尝试根据哪个值向我的 mongodb 聚合添加一个分数name
字段匹配。
例如:如果name
与“sitt”完全匹配,得分为100。
如果name
匹配 /sitt/i,得分为 50。
这是我的代码:
db.getCollection('tags').aggregate([
{
"$match": {
"$or": [
{
"name": "sitt"
},
{
"name": /sitt/i
},
{
"name": /^sitt/i
}
]
}
},
{
"$project": {
"name": 1,
"score": {
"$switch": {
"branches": [
{
"case": {"name": "sitt"},
"then": 100
},
{
"case": {"name": /sitt/i},
"then": 50
}
],
"default": 0
}
}
}
}
])
But the score
结果总是 100。这个陈述总是正确的。
$switch case 是否仅适用于数值?
看起来像{"name": "sitt"}
总是决心true。你应该使用**$eq**
操作员使其工作。
另请注意,您的**$match**
阶段可以简化很多,因为你的 3 个表达式相当于
{$match: {name: /sitt/i}}
所以你的查询变成:
db.getCollection('tags').aggregate([
{
$match:{
name:/sitt/i
}
},
{
$project:{
name: 1,
score:{
$switch:{
branches:[
{
case:{
$eq:[
"$name",
"sitt"
]
},
then:100
}
],
default:50
}
}
}
}
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)