- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $switch (aggregation)
$switch (aggregation)¶
On this page
Definition¶
-
$switch
¶ New in version 3.4.
Evaluates a series of case expressions. When it finds an expression which evaluates to
true
,$switch
executes a specified expression and breaks out of the control flow.$switch
has the following syntax:The objects in the
branches
array must contain only acase
field and athen
field.Operand Description branches
An array of control branch documents. Each branch is a document with the following fields:
case
- Can be any valid expression that resolves to a
boolean
. If the result is not aboolean
, it is coerced to a boolean value. More information about how MongoDB evaluates expressions as either true or false can be found here.
then
- Can be any valid expression.
The
branches
array must contain at least one branch document.default
Optional. The path to take if no branch
case
expression evaluates totrue
.Although optional, if
default
is unspecified and no branchcase
evaluates to true,$switch
returns an error.
Behavior¶
The various case statements do not need to be mutually exclusive.
$switch
executes the first branch it finds which
evaluates to true
. If none of the branches evaluates to true,
$switch
executes the default
option.
The following conditions cause $switch
to fail with an
error:
- The
branches
field is missing or is not an array with at least one entry. - An object in the
branches
array does not contain acase
field. - An object in the
branches
array does not contain athen
field. - An object in the
branches
array contains a field other thancase
orthen
. - No
default
is specified and nocase
evaluates totrue
.
Example | Results |
---|---|
"less than" |
|
"Did not match" |
|
"First case" |