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

$toBool(집계)

이 페이지의 내용

  • 정의
  • 행동
  • 예제
$toBool

값을 부울로 변환합니다.

$toBool 의 구문은 다음과 같습니다:

{
$toBool: <expression>
}

$toBool 는 유효한 표현식을 사용합니다.

$toBool는 다음 $convert 표현식의 약칭입니다.

{ $convert: { input: <expression>, to: "bool" } }

다음도 참조하세요.

다음 표에는 더블로 변환할 수 있는 입력 유형이 나열되어 있습니다.

입력 유형
행동
배열
true를 반환합니다
이진 데이터
true를 반환합니다
부울
아니요. 부울 값을 반환합니다.
코드
true를 반환합니다
날짜
true를 반환합니다
10진수
Returns true if not zero
Return false if zero
더블
Returns true if not zero
Return false if zero
Integer
Returns true if not zero
Return false if zero
JavaScript
true를 반환합니다
Long
Returns true if not zero
Return false if zero
최대 키
true를 반환합니다
최소 키
true를 반환합니다
Null

null 반환

개체
true를 반환합니다
ObjectId
true를 반환합니다
정규 표현식
true를 반환합니다
문자열
true를 반환합니다
타임스탬프
true를 반환합니다

MongoDB의 데이터 유형에 대해 자세히 알아보려면 BSON types를 참조하세요.

다음 표에는 더블로 변환하는 몇 가지 예가 나와 있습니다:

예제
결과
{$toBool: false}
거짓
{$toBool: 1.99999}
true
{$toBool: NumberDecimal("5")}
true
{$toBool: NumberDecimal("0")}
거짓
{$toBool: 100}
true
{$toBool: ISODate("2018-03-26T04:38:28.044Z")}
true
{$toBool: "false"}
true
{$toBool: ""}
true
{$toBool: null}
null

다음 문서를 사용하여 컬렉션 orders를 생성합니다.

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, shipped: true },
{ _id: 2, item: "pie", qty: 10, shipped: 0 },
{ _id: 3, item: "ice cream", shipped: 1 },
{ _id: 4, item: "almonds", qty: 2, shipped: "true" },
{ _id: 5, item: "pecans", shipped: "false" }, // Note: All strings convert to true
{ _id: 6, item: "nougat", shipped: "" } // Note: All strings convert to true
] )

orders 컬렉션에 대한 다음 애그리게이션 작업은 배송되지 않은 주문을 찾기 전에 shipped를 부울 값으로 변환합니다.

// Define stage to add convertedShippedFlag field with the converted shipped value
// Because all strings convert to true, include specific handling for "false" and ""
shippedConversionStage = {
$addFields: {
convertedShippedFlag: {
$switch: {
branches: [
{ case: { $eq: [ "$shipped", "false" ] }, then: false } ,
{ case: { $eq: [ "$shipped", "" ] }, then: false }
],
default: { $toBool: "$shipped" }
}
}
}
};
// Define stage to filter documents and pass only the unshipped orders
unshippedMatchStage = {
$match: { "convertedShippedFlag": false }
};
db.orders.aggregate( [
shippedConversionStage,
unshippedMatchStage
] )

연산은 다음 문서를 반환합니다.

{ "_id" : 2, "item" : "pie", "qty" : 10, "shipped" : 0, "convertedShippedFlag" : false }
{ "_id" : 5, "item" : "pecans", "shipped" : "false", "convertedShippedFlag" : false }
{ "_id" : 6, "item" : "nougat", "shipped" : "", "convertedShippedFlag" : false }

참고

변환 작업에 오류가 발생하면 애그리게이션 작업이 중지되고 오류가 발생합니다. 이 동작을 재정의하려면 $convert 를 대신 사용하세요.

돌아가기

$tanh

다음

$toDate

이 페이지의 내용