[DOCS-9556] Docs for SERVER-10689: Add a $switch expression Created: 05/Dec/16  Updated: 11/Jul/17  Resolved: 11/Jul/17

Status: Closed
Project: Documentation
Component/s: Server
Affects Version/s: None
Fix Version/s: 3.3.5

Type: Task Priority: Major - P3
Reporter: Emily Hall Assignee: Jonathan DeStefano
Resolution: Done Votes: 0
Labels: expression, usability
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Documented
documents SERVER-10689 Add a $switch expression Closed
Participants:
Days since reply: 6 years, 31 weeks, 1 day ago

 Description   

Engineering Ticket 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.

Old Description:
Currently if you want to do a multi-way switch statement equivalent in $project you have to do a very messy embedded sequence of {$cond:[]} statements (emulating an if-elif-elif-elif type sequence) which is very unreadable.

It would be nice to have an operator to do something like:

 'field: {$case:[ {condition1: val1}, {cond2: val2}, etc]}' 

where the first condition that matches sets the value of field to appropriate val.

Asya



 Comments   
Comment by Kay Kim (Inactive) [ 11/Jul/17 ]

this is a duplicate.

Generated at Thu Feb 08 07:58:38 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.