聚合无效运算符'$ switch'

时间:2018-06-13 17:18:39

标签: mongodb mongoose mongodb-query aggregation-framework

使用mongoose与Mongodb和node.js,我想执行一个聚合,需要确定一个值是否基于时间,所以我可以转换为秒,如果是这样,并保持原样,如果不是基于时间。

我在divide运算符中添加了一个$ switch运算符来执行此操作。出于某种原因,我不断收到错误,指出“MongoError:invalid operator'$ 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运算符,那么修复此逻辑的替代方法是什么?

1 个答案:

答案 0 :(得分:2)

如上所述,MongoDB 3.4引入了$switch。虽然升级到那个版本可能是个好主意,但自从使用$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“keys”语法来澄清,但早期的数组语法仍然有效,基本上意味着该语句可以一直写回MongoDB 2.2。

这应该是有道理的,因为任何其他编程语言实现中的“切换”语句仅仅是一种“更清晰”的方式来继续编写if/then/else if,所以有意义的是,任何做同样事情的事情也会产生相同的结果,但只是语法不同。

相关问题