AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

$toBool(式)

$toBool

値をブール値に変換します。

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

{ $toBool: <expression>}

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

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

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

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

入力タイプ
動作

配列

true を返します

バイナリ データ

true を返します

ブール値

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

コード

true を返します

日付

true を返します

小数点

0 でない場合、`true` を返します。
0 の場合、`false` を返します。

Double

0 でない場合、`true` を返します。
0 の場合、`false` を返します。

整数

0 でない場合、`true` を返します。
0 の場合、`false` を返します。

JavaScript

true を返します

Long

0 でない場合、`true` を返します。
0 の場合、`false` を返します。

Max key

true を返します

MinKey

true を返します

null

値が null を返します

オブジェクト

true を返します

ObjectId

true を返します

正規表現

true を返します

文字列

true を返します

タイムスタンプ

true を返します

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

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

例
結果

{$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}

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

このページを評価

項目一覧