定義
$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> ] }
例
このページの例では、付属の sample_mflixサンプルデータセット のデータを使用します。このデータセットを自己管理型MongoDBデプロイにロードする 方法の詳細については、「サンプルデータセットをロードする 」を参照してください。サンプルデータベースに変更を加えた場合、このページの例を実行するには、データベースを削除して再作成する必要がある場合があります。
単一入力式
次の例では、$ifNull を使用して以下を返します。
ratedratedフィールドが 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.ratingtomatoes.critic.ratingが null または欠落しており、tomatoes.viewer.ratingが null 以外の場合。0tomatoes.critic.ratingとtomatoes.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 } ]