AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

$toInt(式演算子)

$toInt

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

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

{ $toInt: <expression>}

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

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

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

次の表で、整数に変換できる入力型を一覧にしています。

入力タイプ
動作

ブール値

false に対して 0 を返します。
true に対して 1 を返します。

Double

切り捨てられた値を返します。

切り捨てられた double 値は、整数値の最小値と最大値の範囲内に収まる必要があります。

切り捨てられた値が最小の整数値より小さい、または最大の整数値より大きい場合、double 値を変換することはできません。

小数点

切り捨てられた値を返します。

切り捨てられた小数値は、整数の最小値と最大値の範囲内に収まる必要があります。

切り捨てられた値が最小整数値より小さい、または最大整数値より大きい 10 進数値は変換できません。

整数

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

Long

long 値を整数として返します。

long 値は整数の最小値と最大値の範囲内になければなりません。

最小整数値より小さい、または最大整数値より大きい long 値を変換することはできません。

文字列

文字列の数値を整数として返します。

文字列の値は 10 進数の整数である必要があります(例: "-5"、"123456")。

浮動小数点数、小数点数、10 進数以外の数値の文字列は変換できません(例: "-5.0"、"0x6400")。

次の表に、整数への変換の例をいくつか示します。

例
結果

$toInt: true

1

$toInt: false

0

$toInt: 1.99999

1

$toInt: Decimal128("5.5000")

5

$toInt: Decimal128("9223372036000.000")

エラー

$toInt: Long("5000")

5,000

$toInt: Long("922337203600")

エラー

$toInt: "-2"

-2

$toInt: "2.5"

エラー

$toInt: null

null

次のドキュメントを使用してコレクション orders を作成します。

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

次の集計操作を行います。

  • qty を整数に変換します。

  • price を小数に変換します。

  • 合計金額を計算します。

// 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 を使用します。

このページを評価

項目一覧