if else if cond in mongodb 聚合

Posted

技术标签:

【中文标题】if else if cond in mongodb 聚合【英文标题】:If else if cond in mongodb aggregation 【发布时间】:2019-02-25 14:31:02 【问题描述】:

我知道以前有人问过这个问题,但我似乎找不到答案,如何在聚合 $project 中添加条件

Schedul.aggregate([
     $match:  flag: 1  ,
    
        $project: 
            "name": "$name",
            "day_of_week": ("$day_of_week" === 0) ? 'Sunday' : ("$day_of_week" === 1) ? 'Monday' : ("$day_of_week" === 2) ? 'Tuesday' : ("$day_of_week" === 3) ? 'Wednesday' : ("$day_of_week" === 4) ? 'Thursday' : ("$day_of_week" === 5) ? 'Friday' : 'Saturday',
        
    ,
])

【问题讨论】:

【参考方案1】:

您可以改用$switch 聚合。

Schedul.aggregate([
   "$match":  "flag": 1 ,
   "$project": 
    "name": "$name",
    "day_of_week": 
      "$switch": 
        "branches": [
           "case":  "$eq": ["$day_of_week", 0] , "then": "Sunday" ,
           "case":  "$eq": ["$day_of_week", 1] , "then": "Monday" ,
           "case":  "$eq": ["$day_of_week", 2] , "then": "Tuesday" ,
           "case":  "$eq": ["$day_of_week", 3] , "then": "Wednesday" ,
           "case":  "$eq": ["$day_of_week", 4] , "then": "Thrusday" ,
           "case":  "$eq": ["$day_of_week", 5] , "then": "Friday" 
        ],
        "default": "Saturday"
      
    
  
])

【讨论】:

以上是关于if else if cond in mongodb 聚合的主要内容,如果未能解决你的问题,请参考以下文章

"$cond"

根据语言语义制作外部语句的“else if”部分?

php if else条件在变量中作为字符串[重复]

SCIP习题 1.1

R中执行if else报错:unexpected 'else' in "else"

javaScript之分支判断与内置对象