[CSHARP-1629] Add a $switch expression Created: 18/Apr/16  Updated: 27/May/22  Resolved: 23/Aug/16

Status: Closed
Project: C# Driver
Component/s: Linq
Affects Version/s: None
Fix Version/s: 2.4

Type: New Feature Priority: Major - P3
Reporter: Rathi Gnanasekaran Assignee: Unassigned
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
depends on SERVER-10689 Add a $switch expression Closed
is depended on by DRIVERS-297 Aggregation Framework Support for 3.4 Closed
Epic Link: MongoDB 3.4
Server Compat: 3.3

 Description   

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.


 Comments   
Comment by Craig Wilson [ 23/Aug/16 ]

The C# compiler doesn't generate switch statements in expression trees. While a user could do this by building an expression tree manually, I don't think the use case is great enough for the amount of effort to implement this.

If someone has a need for this, feel free to re-open the ticket.

NOTE: We do support conditional statements already using the ternary operator .

Generated at Wed Feb 07 21:40:12 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.