$size (집계)
정의
호환성
다음 환경에서 호스팅되는 배포에 $size
사용할 수 있습니다.
MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스
MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전
MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전
구문
$size
의 구문은 다음과 같습니다:
{ $size: <expression> }
$size
의 인수는 배열로 해석되는 한 모든 표현식 이 될 수 있습니다. 표현식에 대한 자세한 내용은 표현식을 참조하세요 .
행동
$size
의 인수는 배열로 해석되어야 합니다. $size
에 대한 인수가 누락되었거나 배열로 확인되지 않으면 $size
오류가 발생합니다.
예시
다음 문서가 포함된 inventory
컬렉션을 생각해 보세요.
db.inventory.insertMany( [ { _id: 1, item: "ABC1", description: "product 1", colors: [ "blue", "black", "red" ] }, { _id: 2, item: "ABC2", description: "product 2", colors: [ "purple" ] }, { _id: 3, item: "XYZ1", description: "product 3", colors: [ ] }, { _id: 4, item: "ZZZ1", description: "product 4 - missing colors" }, { _id: 5, item: "ZZZ2", description: "product 5 - colors is string", colors: "blue,red" } ] )
다음 집계 파이프라인 작업은 $size
연산자를 사용하여 colors
배열의 요소 수를 반환합니다.
db.inventory.aggregate([ { $project: { item: 1, numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} } } } ] )
이 연산은 다음을 반환합니다:
{ _id: 1, item: "ABC1", numberOfColors: 3 } { _id: 2, item: "ABC2", numberOfColors: 1 } { _id: 3, item: "XYZ1", numberOfColors: 0 } { _id: 4, item: "ZZZ1", numberOfColors: "NA" } { _id: 5, item: "ZZZ2", numberOfColors: "NA" }