En MongoDB, el $switch
el operador de canalización de agregación evalúa una serie de case
expresiones, y ejecuta una expresión específica solo cuando un case
expresión se evalúa como true
.
Sintaxis
La sintaxis es así:
$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> },
...
],
default: <expression>
}
Ejemplo
Supongamos que tenemos una colección llamada pets
con los siguientes documentos:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Kangaroo", "weight" : 100 } { "_id" : 6, "name" : "Hop", "type" : "Kangaroo", "weight" : 130 } { "_id" : 7, "name" : "Punch", "type" : "Kangaroo", "weight" : 200 } { "_id" : 8, "name" : "Snap", "type" : "Cat", "weight" : 12 } { "_id" : 9, "name" : "Ruff", "type" : "Dog", "weight" : 30 }
Podemos usar el $switch
operador para ejecutar algunas expresiones de caso contra el weight
campo:
db.pets.aggregate(
[
{
$project:
{
_id: 0,
weight: 1,
result: {
$switch: {
branches: [
{ case: { $gt: [ "$weight", 100 ] }, then: "Heavy" },
{ case: { $lt: [ "$weight", 20 ] }, then: "Light" }
],
default: "Medium"
}
}
}
}
]
)
Resultado:
{ "weight" : 20, "result" : "Medium" } { "weight" : 10, "result" : "Light" } { "weight" : 7, "result" : "Light" } { "weight" : 8, "result" : "Light" } { "weight" : 100, "result" : "Medium" } { "weight" : 130, "result" : "Heavy" } { "weight" : 200, "result" : "Heavy" } { "weight" : 12, "result" : "Light" } { "weight" : 30, "result" : "Medium" }
Omitir la expresión predeterminada
Omitir el default
del código puede resultar en un error. Pero esto depende del resultado del case
expresiones.
Si eliminamos el default
parte del ejemplo anterior, obtenemos un error:
db.pets.aggregate(
[
{
$project:
{
_id: 0,
weight: 1,
result: {
$switch: {
branches: [
{ case: { $gt: [ "$weight", 100 ] }, then: "Heavy" },
{ case: { $lt: [ "$weight", 20 ] }, then: "Light" }
]
}
}
}
}
]
)
Resultado:
uncaught exception: Error: command failed: { "ok" : 0, "errmsg" : "$switch could not find a matching branch for an input, and no default was specified.", "code" : 40066, "codeName" : "Location40066" } : aggregate failed : [email protected]/mongo/shell/utils.js:25:13 [email protected]/mongo/shell/assert.js:18:14 [email protected]/mongo/shell/assert.js:639:17 [email protected]/mongo/shell/assert.js:729:16 [email protected]/mongo/shell/db.js:266:5 [email protected]/mongo/shell/collection.js:1058:12 @(shell):1:1
En este caso, había valores de entrada que no estaban cubiertos por el case
expresiones (es decir, aquellas entre 20 y 100), y así $switch
devolvió un error.
Sin embargo, si cambiamos el case
ligeramente, podemos eliminar el default
parte sin error:
db.pets.aggregate(
[
{
$project:
{
_id: 0,
weight: 1,
result: {
$switch: {
branches: [
{ case: { $gt: [ "$weight", 100 ] }, then: "Heavy" },
{ case: { $lte: [ "$weight", 100 ] }, then: "Light" }
]
}
}
}
}
]
)
Resultado:
{ "weight" : 20, "result" : "Light" } { "weight" : 10, "result" : "Light" } { "weight" : 7, "result" : "Light" } { "weight" : 8, "result" : "Light" } { "weight" : 100, "result" : "Light" } { "weight" : 130, "result" : "Heavy" } { "weight" : 200, "result" : "Heavy" } { "weight" : 12, "result" : "Light" } { "weight" : 30, "result" : "Light" }
En este ejemplo, todos los documentos cumplieron todos los case
expresiones, por lo que default
no era necesario, lo que significaba que no se producía ningún error.
Documentación de MongoDB
Consulte la documentación de MongoDB para obtener más detalles y ejemplos.