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 배포를 위한 완전 관리형 서비스

{
$ifNull: [
<input-expression-1>,
...
<input-expression-n>,
<replacement-expression-if-null>
]
}

이 페이지의 예제에서는 sample_mflix 샘플 데이터 세트 의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB deployment 에 로드하는 방법에 대한 자세한 내용은 샘플 데이터 세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우 이 페이지의 예제를 실행 하려면 데이터베이스를 삭제하고 다시 만들어야 할 수 있습니다.

다음 예시에서는 $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

이 페이지의 내용