Definition
$switchEvaluates a series of case expressions. When it finds an expression which evaluates to
true,$switchexecutes a specified expression and breaks out of the control flow.$switchhas the following syntax:$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression> } The objects in the
branchesarray must contain only acasefield and athenfield.OperandDescriptionbranchesAn 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
branchesarray must contain at least one branch document.defaultOptional. The path to take if no branch
caseexpression evaluates totrue.Although optional, if
defaultis unspecified and no branchcaseevaluates to true,$switchreturns 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
branchesfield is missing or is not an array with at least one entry.An object in the
branchesarray does not contain acasefield.An object in the
branchesarray does not contain athenfield.An object in the
branchesarray contains a field other thancaseorthen.No
defaultis specified and nocaseevaluates totrue.
Example | Results | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||
|
| |||||||||
|
|
Example
The following example uses the movies collection from the sample_mflix
sample dataset. For details on how to load this dataset into your deployment, see Load the sample dataset.
This aggregation operation uses $switch to display a particular message based on each movie's rating. The $match stage limits the results to the three longest movies in the sample dataset:
db.movies.aggregate( [ { $match: { runtime: { $gt: 800 } } }, { $project: { _id: 0, title: 1, summary: { $switch: { branches: [ { case: { $gte: [ "$imdb.rating", 9 ] }, then: "Doing great!" }, { case: { $and: [ { $gte: [ "$imdb.rating", 8 ] }, { $lt: [ "$imdb.rating", 9 ] } ] }, then: "Doing pretty well." }, { case: { $lt: [ "$imdb.rating", 8 ] }, then: "Needs improvement." } ], default: "No rating found." } } } }, { $sort: { title: 1 } } ] )
[ { title: 'Baseball', summary: 'Doing great!' }, { title: 'Centennial', summary: 'Doing pretty well.' }, { title: 'Taken', summary: 'Needs improvement.' } ]
Tip