mongodb - 聚合无效运算符'$switch'
问题描述
将 mongoose 与 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
连续写作方式,所以任何做同样事情的东西也会产生相同的结果但只是语法不同是有道理的.
推荐阅读
- flutter - JWT Auth 和 Flutter:如何访问单个模型数据
- postgresql - Azure Postgres AUTOVACUM AND ANALYZE THRESHOLD - 如何更改它?
- vue.js - 如何在 created() 上传递状态 vuex
- sql - 如果存在匹配值,则从另一个表中检索数据 - 否则基于第一个连接条件返回
- java - 如何按任何字段搜索 Firebase 数据库?
- reactjs - 无法设置未定义 TypeScript/React 的属性
- assembly - 如何通过添加两个数字来修复装配 at&t 分段错误
- import - 在活动浏览器中读取 ecospold2 文件时出现问题
- python - 尽管传递了自定义对象,但无法在使用 `tf.keras.models.load_model()` 加载的模型上使用 `call()`
- php - WP_QUERY,ARRAYS,如果有多个类别,则重复帖子