聚合无效运算符"$switch"



将猫鼬与Mongodb和node.js一起使用,我想执行一个聚合,该聚合需要确定值是否基于时间,以便我可以转换为秒(如果是(,如果不是基于时间,则保持原样。

我在除法运算符中添加了一个$switch运算符来执行此操作。 出于某种原因,我不断收到一个错误,指示"MongoError:无效的运算符'$switch'"。

代码如下所示:

$divide: [{
$switch: {
branches: [
{
case: { $eq: [ "$timeType", "min"]},
then: { $multiply: [ "$route.completedTotal", "60" ] }
},
{
case: { $eq: [ "$timeType", "sec"]},
then: "$route.completedTotal"
},
{
case: { $eq: [ "$timeType", "hr"]},
then: { $multiply: [ "$route.completedTotal", "3600" ] }
}
],
default: "$route.completedTotal"
}
}, {
$switch: {
branches: [
{
case: { $eq: [ "$timeType", "min"]},
then: { $multiply: [ "$route.total", "60" ] }
},
{
case: { $eq: [ "$timeType", "sec"]},
then: "$route.total"
},
{
case: { $eq: [ "$timeType", "hr"]},
then: { $multiply: [ "$route.total", "3600" ] }
}
],
default: "$route.total"
}
}]

如何修复我的$switch运算符以使其正常工作? 如果我不能在此上下文中使用 $switch 运算符,那么修复此逻辑的替代方法是什么?

如前所述,$switch是在MongoDB 3.4中引入的。虽然尽可能升级到该版本可能是个好主意,但自从使用$cond发布聚合框架以来,相同的语句一直是可能的:

"$divide": [
{
"$cond": {
"if": { "$eq": [ "$timeType", "min" ] },
"then" { "$multiply": [ "$route.completedTotal", "60" ] },
"else": {
"$cond": {
"if": { "$eq": [ "$timeType", "sec"] },
"then": "$route.completedTotal",
"else": {
"$cond": {
"if": { "$eq": [ "$timeType", "hr"] },
"then": { "$multiply": [ "$route.completedTotal", "3600" ] },
"else": "$route.completedTotal"
}
}
}
}
}
},
{
"$cond": {
"if": { "$eq": [ "$timeType", "min" ] },
"then": { "$multiply": [ "$route.total", "60" ] },
"else": {
"$cond": {
"if": { "$eq": [ "$timeType", "sec" ] },
"then": "$route.total",
"else": {
"$cond": {
"if": { "$eq": [ "$timeType", "hr" ] },
"then": { "$multiply": [ "$route.total", "3600" ] },
"else": "$route.total"
}
}
}
}
}
}
]

这是使用if/then/else"键"语法来澄清,但早期的数组语法仍然有效,基本上意味着该语句可以一直写回MongoDB 2.2。

这应该是有意义的,因为任何其他编程语言实现中的"switch"语句只是一种"更干净"的if/then/else if继续编写的方式,因此任何做同样事情的东西也会产生相同的结果,但只是语法不同。

最新更新