gpt4 book ai didi

mongodb - 使用 $switch 将分数添加到 MongoDB 聚合

转载 作者:可可西里 更新时间:2023-11-01 10:02:30 26 4
gpt4 key购买 nike

我正在尝试根据 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
}
}
}
}
])

但是 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
}
}
}
}
])

关于mongodb - 使用 $switch 将分数添加到 MongoDB 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45082630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com