$ifNull(集計)
定義
バージョン 5.0 での変更。
$ifNull
式は入力式を null 値として評価し、次を返します。
$ifNull
未定義の値と欠落したフィールドは null として扱われます。
互換性
次の環境でホストされる配置には $ifNull
を使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
{ $ifNull: [ <input-expression-1>, ... <input-expression-n>, <replacement-expression-if-null> ] }
例
この inventory
コレクションは、次の例で使用されています。
db.inventory.insertMany( [ { _id: 1, item: "buggy", description: "toy car", quantity: 300 }, { _id: 2, item: "bicycle", description: null, quantity: 200 }, { _id: 3, item: "flag" } ] )
単一入力式
次の例では、$ifNull
を使用して以下を返します。
description
null 以外の場合。"Unspecified"
description
がNULLまたは見つからない場合は文字列。
db.inventory.aggregate( [ { $project: { item: 1, description: { $ifNull: [ "$description", "Unspecified" ] } } } ] )
出力:
{ _id: 1, item: "buggy", description: "toy car" } { _id: 2, item: "bicycle", description: "Unspecified" } { _id: 3, item: "flag", description: "Unspecified" }
複数の入力式
バージョン 5.0 で追加
次の例では、$ifNull
を使用して以下を返します。
description
null 以外の場合。quantity
description
が null または欠落しており、quantity
が null 以外の場合。"Unspecified"
文字列とdescription
とquantity
の両方が null または欠落している場合は文字列です。
db.inventory.aggregate( [ { $project: { item: 1, value: { $ifNull: [ "$description", "$quantity", "Unspecified" ] } } } ] )
出力:
{ _id: 1, item: "buggy", value: "toy car" } { _id: 2, item: "bicycle", value: 200 } { _id: 3, item: "flag", value: "Unspecified" }