MongoDB 4.0から、$toBoolを使用できます 値をブール値に変換する集約パイプライン演算子。
値をブール値に変換すると、結果はtrueになります。 またはfalse 、入力値によって異なります。
通常、数値の場合、これはfalseを返します。 値がゼロの場合(0 )、およびtrue その他の値の場合。
string、ObjectId、およびDateの値の場合、常にtrueを返します。 。
例
typesというコレクションがあるとします。 次のドキュメントが含まれています:
{
"_id" : ObjectId("60133e50c8eb4369cf6ad9d9"),
"double" : 123.75,
"string" : "123",
"boolean" : true,
"date" : ISODate("2020-12-31T23:30:15.123Z"),
"integer" : 123,
"long" : NumberLong(123),
"decimal" : NumberDecimal("123.75")
}
{
"_id" : ObjectId("60133e50c8eb4369cf6ad9da"),
"double" : 0,
"string" : "",
"boolean" : false,
"date" : null,
"integer" : 0,
"long" : NumberLong(0),
"decimal" : NumberDecimal("0.0")
}
$toBoolを使用できます これらすべての型をブール値に変換する演算子。入力がブール値の場合、単にブール値を返します。
db.types.aggregate(
[
{
$project:
{
_id: 0,
objectId: { $toBool: "$_id" },
double: { $toBool: "$double" },
string: { $toBool: "$string" },
boolean: { $toBool: "$boolean" },
date: { $toBool: "$date" },
integer: { $toBool: "$integer" },
long: { $toBool: "$long" },
decimal: { $toBool: "$decimal" }
}
}
]
).pretty() 結果:
{
"objectId" : true,
"double" : true,
"string" : true,
"boolean" : true,
"date" : true,
"integer" : true,
"long" : true,
"decimal" : true
}
{
"objectId" : true,
"double" : false,
"string" : true,
"boolean" : false,
"date" : null,
"integer" : false,
"long" : false,
"decimal" : false
}
最初のドキュメントのすべての値がtrueを返したことがわかります 、しかし、2番目のドキュメントの多くはfalseを返しました 。また、日付値はnullを返しました nullだったから はじめに。
エラー
エラーが発生した場合は、$convertを使用してみてください $toBoolの代わりに演算子 。 $convert 演算子を使用すると、集計操作全体に影響を与えることなくエラーを処理できます。
$toBool 演算子は、$convertを使用するのと同じです 値をブール値に変換する演算子。
$convertの使用例を次に示します。 文字列をブール値に変換するには::
db.types.aggregate(
[
{
$project:
{
_id: 0,
result:
{
$convert: {
input: "$string",
to: "bool",
onError: "An error occurred",
onNull: "Input was null or empty"
}
}
}
}
]
) 結果:
{ "result" : true }
MongoDB $convertを参照してください その他の例については。