$toBool (aggregation)
On this page本页内容
Definition定义
$toBool-
Converts a value to a boolean.将值转换为布尔值。$toBoolhas the following syntax:具有以下语法:{
$toBool: <expression>
}The$toBooltakes any valid expression.$toBool接受任何有效的表达式。The$toBoolis a shorthand for the following$convertexpression:$toBool是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "bool" } }TipSee also:另请参阅:
Behavior行为
The following table lists the input types that can be converted to a boolean:下表列出了可以转换为布尔值的输入类型:
| Boolean | |
| Double | true。false。 |
| Decimal | true。false。 |
| Integer | true。false。 |
| Long | true。false。 |
| ObjectId | true。 |
| String | true。 |
| Date | true。 |
The following table lists some conversion to boolean examples:下表列出了一些转换为布尔值的示例:
{$toBool: false} | false |
{$toBool: 1.99999} | true |
{$toBool: NumberDecimal("5")} | true |
{$toBool: NumberDecimal("0")} | false |
{$toBool: 100} | true |
{$toBool: ISODate("2018-03-26T04:38:28.044Z")} | true |
{$toBool: "false"} | true |
{$toBool: ""} | true |
{$toBool: null} | null |
Example实例
Create a collection 使用以下文档创建集合orders with the following documents:orders:
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
] )
The following aggregation operation on the 在查找未发货的订单之前,orders collection converts the shipped to a boolean value before finding the unshipped orders:orders集合上的以下聚合操作将shipped转换为布尔值:
// 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
] )
The operation returns the following document:该操作返回以下文档:
{ "_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 }