Docs Menu
Docs Home
/ /
Operadores de tuberías de agregación

$toBool (agregación)

$toBool

Convierte un valor en un booleano.

$toBool tiene la siguiente sintaxis:

{
$toBool: <expression>
}

El toma cualquier valor $toBool válido expresión.

$toBool es una abreviatura de la siguiente $convert expresión:

{ $convert: { input: <expression>, to: "bool" } }

Tip

La siguiente tabla enumera los tipos de entrada que se pueden convertir a un valor booleano:

Tipo de entrada
Comportamiento

Arreglo

Devuelve verdadero

Datos binarios

Devuelve verdadero

Booleano

No-op. Devuelve el valor booleano.

Código

Devuelve verdadero

fecha

Devuelve verdadero

Decimal

Returns true if not zero
Return false if zero

Double

Returns true if not zero
Return false if zero

entero

Returns true if not zero
Return false if zero

JavaScript

Devuelve verdadero

Long

Returns true if not zero
Return false if zero

MaxKey

Devuelve verdadero

MinKey

Devuelve verdadero

Nulo

Devuelve nulo

Objeto

Devuelve verdadero

ObjectId

Devuelve verdadero

Expresión regular

Devuelve verdadero

String

Devuelve verdadero

Marca de tiempo

Devuelve verdadero

Para obtener más información sobre los tipos de datos en MongoDB, consulte Tipos BSON.

La siguiente tabla enumera algunos ejemplos de conversión a valores booleanos:

Ejemplo
Resultados

{$toBool: false}

false

{$toBool: 1.99999}

true

{$toBool: Decimal128("5")}

true

{$toBool: Decimal128("0")}

false

{$toBool: 100}

true

{$toBool: ISODate("2018-03-26T04:38:28.044Z")}

true

{$toBool: "false"}

true

{$toBool: ""}

true

{$toBool: null}

nulo

Cree una colección orders con los siguientes documentos:

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, shipped: true },
{ _id: 2, item: "pie", qty: 10, shipped: 0 },
{ _id: 3, item: "ice cream", shipped: 1 },
{ _id: 4, item: "almonds", qty: 2, shipped: "true" },
{ _id: 5, item: "pecans", shipped: "false" }, // Note: All strings convert to true
{ _id: 6, item: "nougat", shipped: "" } // Note: All strings convert to true
] )

La siguiente operación de agregación en la colección orders convierte shipped en un valor booleano antes de encontrar los pedidos no enviados:

// Define stage to add convertedShippedFlag field with the converted shipped value
// Because all strings convert to true, include specific handling for "false" and ""
shippedConversionStage = {
$addFields: {
convertedShippedFlag: {
$switch: {
branches: [
{ case: { $eq: [ "$shipped", "false" ] }, then: false } ,
{ case: { $eq: [ "$shipped", "" ] }, then: false }
],
default: { $toBool: "$shipped" }
}
}
}
};
// Define stage to filter documents and pass only the unshipped orders
unshippedMatchStage = {
$match: { "convertedShippedFlag": false }
};
db.orders.aggregate( [
shippedConversionStage,
unshippedMatchStage
] )

La operación devuelve el siguiente documento:

{ "_id" : 2, "item" : "pie", "qty" : 10, "shipped" : 0, "convertedShippedFlag" : false }
{ "_id" : 5, "item" : "pecans", "shipped" : "false", "convertedShippedFlag" : false }
{ "_id" : 6, "item" : "nougat", "shipped" : "", "convertedShippedFlag" : false }

Nota

Si la operación de conversión detecta un error, la operación de agregación se detiene y genera un error. Para anular este comportamiento,$convert utilice.

Volver

$tanh

En esta página