このバージョンのドキュメントはアーカイブされており、サポートされなくなりました。5.0 配置をアップグレードするには、 MongoDB 6.0 のアップグレード手順 を参照してください。
定義
バージョン 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 を使用して以下を返します。
- descriptionnull 以外の場合。
- "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 を使用して以下を返します。
- descriptionnull 以外の場合。
- 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" }