Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

$ifNull(式演算子)

$ifNull

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

このページの例では、付属の sample_mflixサンプルデータセット のデータを使用します。このデータセットを自己管理型MongoDBデプロイにロードする 方法の詳細については、「サンプルデータセットをロードする 」を参照してください。サンプルデータベースに変更を加えた場合、このページの例を実行するには、データベースを削除して再作成する必要がある場合があります。

次の例では、$ifNull を使用して以下を返します。

  • rated ratedフィールドが null 以外の場合。

  • "Not Rated" ratedがNULLまたは見つからない場合は文字列。

db.movies.aggregate(
[
{ $match: { year: { $lt: 1910 } } },
{
$project: {
_id: 0,
title: 1,
rated: { $ifNull: [ "$rated", "Not Rated" ] }
}
},
{ $sort: { title: 1 } }
]
)
[
{ title: 'A Corner in Wheat', rated: 'G' },
{ title: 'The Great Train Robbery', rated: 'TV-G' },
{ title: 'The Kiss', rated: 'Not Rated' },
{ title: 'The Kiss', rated: 'Not Rated' }
]

バージョン 5.0 で追加

次の例では、$ifNull を使用して以下を返します。

  • tomatoes.critic.rating 非 null の場合。

  • tomatoes.viewer.rating tomatoes.critic.ratingが null または欠落しており、 tomatoes.viewer.ratingが null 以外の場合。

  • 0 tomatoes.critic.ratingtomatoes.viewer.rating の両方が null または欠落している場合。

db.movies.aggregate(
[
{ $match: { year: { $lt: 1910 } } },
{
$project: {
_id: 0,
title: 1,
rating: { $ifNull: [ "$tomatoes.critic.rating", "$tomatoes.viewer.rating", 0 ] }
}
},
{ $sort: { title: 1 } }
]
)
[
{ title: 'A Corner in Wheat', rating: 3.6 },
{ title: 'The Great Train Robbery', rating: 7.6 },
{ title: 'The Kiss', rating: 4 },
{ title: 'The Kiss', rating: 0 }
]

戻る

$hour

項目一覧