我正在尝试根据 name
字段匹配的值向我的 mongodb 聚合添加分数。
例如:如果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
}
}
}
}
])
但是分数
总是100。这个陈述总是正确的。
$switch 大小写是否仅用于数值?
最佳答案
看起来{"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
}
}
}
}
])
关于mongodb - 使用 $switch 将分数添加到 MongoDB 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45082630/