Docs Menu

$toDecimal(集計)

項目一覧

$toDecimal

値を小数に変換します。値を 10 進数に変換できない場合は、 $toDecimal エラーが発生します。また、値が null または欠落している場合、$toDecimal は null を返します。

$toDecimal の構文は次のとおりです。

{
$toDecimal: <expression>
}

$toDecimalは任意の有効な式を受け入れます。

$toDecimal は次の $convert 式の省略形です。

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

以下も参照してください。

以下の表は、10 進数に変換できる入力型の一覧です。

入力タイプ
動作

ブール値

Returns Decimal128("0") for false.
Returns Decimal128("1") for true.

Double

double 値を小数として返します。

小数点

何も起こりません。小数を返します。

整数

int 値を小数で返します。

Long

long 値を小数で返します。

文字列

文字列の数値を小数で返します。

文字列の値は 10 進数の数値でなければなりません(例: "-5.5""123456")。

10 進数以外の数の文字列値は変換できません(例: "0x6400"

日付

日付値に対応する UNIXエポックからのミリ秒数を返します。

次の表に 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 コレクションに対する次の集計操作では、合計価格を計算する前に、price を 10 進数に、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 を使用します。

項目一覧