Docs Menu
Docs Home
/
MongoDB マニュアル
/ / /

$ifNull(集計)

項目一覧

  • 定義
  • 互換性
  • 構文
$ifNull

バージョン 5.0 での変更

$ifNull式は入力式を null 値として評価し、次を返します。

  • 最初の null 以外の入力の値が見つかりました。

  • すべての入力が 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" 文字列とdescriptionquantityの両方が 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" }

戻る

$hour