如果在congo中进行cond

时间:2018-09-21 08:09:11

标签: node.js mongodb express mongoose aggregation-framework

我知道这已经被问过了,但是我似乎找不到答案,如何在总计$ 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 个答案:

答案 0 :(得分: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"
      }
    }
  }}
])