文档菜单
文档首页
/
MongoDB 手册
/ / /

$toBool (聚合)

本页内容

  • 定义
  • 行为
  • 示例
$toBool

将值转换为布尔值。

$toBool的语法如下

{
$toBool: <expression>
}

$toBool 可以接受任何有效的表达式.

$toBool 是以下 $convert 表达式的简写

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

提示

另请参阅

以下表格列出了可以转换为布尔值的输入类型

输入类型
行为
数组
返回 true
二进制数据
返回 true
布尔值
无操作。返回布尔值。
代码
返回 true
日期
返回 true
十进制
如果不为零则返回 true
如果为零则返回 false
双精度浮点数
如果不为零则返回 true
如果为零则返回 false
整数
如果不为零则返回 true
如果为零则返回 false
JavaScript
返回 true
长整型
如果不为零则返回 true
如果为零则返回 false
最大键
返回 true
最小键
返回 true
空值

返回 null

对象
返回 true
对象ID
返回 true
正则表达式
返回 true
字符串
返回 true
时间戳
返回 true

有关 MongoDB 中的数据类型更多信息,请参阅 BSON 类型。

以下表格列出了一些布尔值转换的示例

示例
结果
{$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

创建一个包含以下文档的集合 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
] )

以下对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
] )

该操作返回以下文档

{ "_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 }

注意

如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请使用$convert

返回

双曲正切

本页内容