gpt4 book ai didi

node.js - mongodb 聚合中的 if else if cond

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:36 24 4
gpt4 key购买 nike

我知道以前有人问过这个问题,但我似乎找不到答案,如何在聚合 $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',
}
},
])

最佳答案

您可以使用$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"
}
}
}}
])

关于node.js - mongodb 聚合中的 if else if cond,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52439344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com