Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-1629

Add a $switch expression

    • Type: Icon: New Feature New Feature
    • Resolution: Won't Fix
    • Priority: Icon: Major - P3 Major - P3
    • 2.4
    • Affects Version/s: None
    • Component/s: Linq
    • Labels:
      None

      Syntax

          {$project: {
              fieldName: {
                  $switch: {
                      branches: [
                          {
                              case: <expression>,
                              then: <expression>
                          },
                          …
                      ],
                      default: <optional, expression>
                  }
              }
          }}
      

      Examples

      > db.coll.insert([
        {_id: 0, x: 0}
        {_id: 1, x: -1}
        {_id: 2, x: 2}
      ]);
      > db.coll.aggregate([{
        $project: {
          z: {
            $switch: {
              branches: [
                {
                  case: {$eq: ["$x", 0]},
                  then: "Equal to zero."
                },
                {
                  case: {$eq: [{$abs: "$x"}, 1]},
                  then: "Equal to plus or minus one."
                },
              ],
              default: "Something else."
            }
          }
        }
      }])
      {_id: 0, z: "Equal to zero."}
      {_id: 1, z: "Equal to plus or minus one."}
      {_id: 2, z: "Something else."}
      

      Notes

      • Allows $project expressions to be written without convoluted $conds.
      • If "case" does not return a boolean, the value will be coerced to a bool.
      • Since each case does not have to be mutually exclusive, an input will enter the first branch it matches.
        Errors
      • 'branches' is missing or not an array with at least one entry.
      • An entry in 'branches' does not contain 'case'
      • An entry in 'branches' does not contain 'then'
      • If 'default' is not specified, and an input doesn't match, an error will be thrown.

            Assignee:
            Unassigned Unassigned
            Reporter:
            rathi.gnanasekaran Rathi Gnanasekaran
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: