문서 메뉴

문서 홈애플리케이션 개발MongoDB 매뉴얼

$toDecimal(집계)

이 페이지의 내용

  • 정의
  • 행동
  • 예제
$toDecimal

값을 10진수로 변환합니다. 값을 10진수로 변환할 수 없는 경우 $toDecimal 오류가 발생합니다. 값이 null이거나 누락된 경우 $toDecimal 은 null을 반환합니다.

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

{
$toDecimal: <expression>
}

$toDecimal 는 모든 유효한 표현식을 사용합니다.

$toDecimal 은 다음 $convert 표현식의 약어입니다.

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

다음도 참조하세요.

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

입력 유형
행동
부울
false인 경우 Decimal128("0")를 반환합니다.
true인 경우 Decimal128("1")를 반환합니다.
더블
Double 값을 10진수로 반환합니다.
10진수
아니요. 소수를 반환합니다.
Integer
int 값을 10진수로 반환합니다.
Long
Long 값을 10진수로 반환합니다.
문자열

문자열의 숫자 값을 10진수로 반환합니다.

문자열 값은 10을 기본으로 하는 숫자 값이어야 합니다(예 "-5.5", "123456").

기본 10이 아닌 숫자의 문자열 값은 변환할 수 없습니다(예 "0x6400")

날짜
날짜 값에 해당하는 epoch 이후의 밀리초 수를 반환합니다.

다음 표에는 10진수로 변환하는 몇 가지 예가 나와 있습니다:

예제
결과
{$toDecimal: true}
Decimal128("1")
{$toDecimal: false}
Decimal128("0")
{$toDecimal: 2.5}
Decimal128("2.50000000000000")
{$toDecimal: NumberInt(5)}
Decimal128("5")
{$toDecimal: NumberLong(10000)}
Decimal128("10000")
{$toDecimal: "-5.5"}
Decimal128("-5.5")
{$toDecimal: ISODate("2018-03-27T05:04:47.890Z")}
Decimal128("1522127087890")

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

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, price: 10 },
{ _id: 2, item: "pie", qty: 10, price: NumberDecimal("20.0") },
{ _id: 3, item: "ice cream", qty: 2, price: "4.99" },
{ _id: 4, item: "almonds", qty: 5, price: 5 }
] )

orders collection에 대한 다음 집계 작업은 총 가격을 계산하기 전에 price를 소수로 변환하고 qty를 정수로 변환합니다.

// Define stage to add convertedPrice and convertedQty fields with the converted price and qty values
priceQtyConversionStage = {
$addFields: {
convertedPrice: { $toDecimal: "$price" },
convertedQty: { $toInt: "$qty" },
}
};
// Define stage to calculate total price by multiplying convertedPrice and convertedQty fields
totalPriceCalculationStage = {
$project: { item: 1, totalPrice: { $multiply: [ "$convertedPrice", "$convertedQty" ] } }
};
db.orders.aggregate( [
priceQtyConversionStage,
totalPriceCalculationStage
] )

이 작업은 다음 문서를 반환합니다.

{ _id: 1, item: 'apple', totalPrice: Decimal128("50") },
{ _id: 2, item: 'pie', totalPrice: Decimal128("200.0") },
{ _id: 3, item: 'ice cream', totalPrice: Decimal128("9.98") },
{ _id: 4, item: 'almonds', totalPrice: Decimal128("25") }

참고

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

← toDate(집계)

이 페이지의 내용