Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$toBool(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toBool

将数值转换为布尔值。

$toBool 通过以下语法实现:

{
$toBool: <expression>
}

$toBool可采用任何有效表达式。

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

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

提示

另请参阅:

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

输入类型
行为
阵列
返回 true
二进制数据
返回 true
布尔
不操作。返回布尔值。
代码
返回 true
Date
返回 true
Decimal 数据类型
如果不为零,则返回 true
如果为零,则返回 false
双精度
如果不为零,则返回 true
如果为零,则返回 false
整型
如果不为零,则返回 true
如果为零,则返回 false
JavaScript
返回 true
长整型
如果不为零,则返回 true
如果为零,则返回 false
MaxKey
返回 true
MinKey
返回 true
null

返回 null

对象
返回 true
ObjectId
返回 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

← $tanh(聚合)

在此页面上