$ifNull (집계)
정의
버전 5.0에서 변경됨
$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> ] }
예시
이 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
을 사용하여 반환합니다.
null이 아닌 경우
description
입니다.description
이 null이거나 누락된 경우"Unspecified"
문자열.
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
을 사용하여 반환합니다.
null이 아닌 경우
description
입니다.description
이 null이거나 누락되고quantity
는 null이 아닌 경우quantity
.description
과quantity
가 모두 null이거나 누락된 경우"Unspecified"
문자열.
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" }