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 聚合的主要内容,如果未能解决你的问题,请参考以下文章