문서 메뉴
문서 홈
/
MongoDB 매뉴얼
/ / /

$ifNull (애그리게이션)

이 페이지의 내용

  • 정의
  • 호환성
  • 구문
  • 예제
$ifNull

버전 5.0에서 변경됨

$ifNull 표현식은 다음과 같이 입력 표현식의 null 값 및 반환 결과를 반환합니다.

  • 첫 번째 null이 아닌 입력 표현식 값을 찾았습니다.

  • 모든 입력 표현식이 null로 평가되는 경우를 위한 대체 표현식 값입니다.

$ifNull 정의되지 않은 값과 누락된 필드를 null로 처리합니다.

다음 환경에서 호스팅되는 배포에 $ifNull 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 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

다음

$in

이 페이지의 내용