ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

$toBool (aggregation)

項目一覧

$toBool

Converts a value to a boolean.

$toBoolの構文は次のとおりです。

{
$toBool: <expression>
}

$toBool は任意の有効なを受け入れます。

$toBool は次の $convert 式の省略形です。

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

以下も参照してください。

次の表でブール値に変換できる入力型を一覧にしています。

入力タイプ
動作

配列

true を返します

バイナリ データ

true を返します

ブール値

何も起こりません。ブール値を返します。

コード

true を返します

日付

true を返します

小数点

Returns true if not zero
Return false if zero

Double

Returns true if not zero
Return false if zero

整数

Returns true if not zero
Return false if zero

JavaScript

true を返します

Long

Returns true if not zero
Return false if zero

Max key

true を返します

MinKey

true を返します

null

Returns null

オブジェクト

true を返します

ObjectId

true を返します

正規表現

true を返します

文字列

true を返します

タイムスタンプ

true を返します

MongoDB のデータ型の詳細については、「BSON types」をご覧ください。

次の表でブール値への変換例を一覧にしています。

結果

{$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
] )

The following aggregation operation on the orders collection converts the shipped to a boolean value before finding the unshipped orders:

// 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 を使用します。

項目一覧