Docs Menu
Docs Home
/
MongoDB マニュアル
/ / /

$toLong(集計)

項目一覧

  • 定義
  • 動作
$toLong

値を long に変換します。 値を long に変換できない場合は、 $toLongがエラーになります。 値が null または欠落している場合、 $toLongは null を返します。

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

{
$toLong: <expression>
}

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

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

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

Tip

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

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

入力タイプ
動作
ブール値
Returns Long(0) for false.
Returns Long(1) for true.
Double

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

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

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

小数点

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

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

切り捨てた 10 進数値が最小の long 値より小さい、または最大の long 値より大きい場合、10 進値は変換できません。

整数
整数値を long として返します。
Long
何も起こりません。long 値を返します。
文字列

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

文字列値は 10 進数の long 値で(例えば"-5""123456")。

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

日付
Date をUNIXエポックを基準としたミリ秒数に変換します。

次の表で long 値への変換例の一部を一覧にしています。

結果
{ $toLong: true }
Long("1")
{ $toLong: false }
Long("0")
{ $toLong: 1.99999 }
Long("1")
{ $toLong: NumberDecimal("5.5000") }
Long("5")
{ $toLong: NumberDecimal("9223372036854775808.0") }
エラー
{ $toLong: NumberInt(8) }
Long(8)
{ $toLong: ISODate("2018-03-26T04:38:28.044Z") }
Long("1522039108044")
{ $toLong: "-2" }
Long("-2")
{ $toLong: "2.5" }
エラー
{ $toLong: null }
null

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

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: NumberInt(5) },
{ _id: 2, item: "pie", qty: "100" },
{ _id: 3, item: "ice cream", qty: NumberLong("500") },
{ _id: 4, item: "almonds", qty: "50" },
] )

ordersコレクションに対する次の集計操作では、値で並べ替える前にqtyを long に変換します。

// Define stage to add convertedQty field with converted qty value
qtyConversionStage = {
$addFields: {
convertedQty: { $toLong: "$qty" }
}
};
// Define stage to sort documents by the converted qty values
sortStage = {
$sort: { "convertedQty": -1 }
};
db.orders.aggregate( [
qtyConversionStage,
sortStage
])

この操作により、次のドキュメントが返されます。

{ _id: 3, item: 'ice cream', qty: Long("500"), convertedQty: Long("500") },
{ _id: 2, item: 'pie', qty: '100', convertedQty: Long("100") },
{ _id: 4, item: 'almonds', qty: '50', convertedQty: Long("50") },
{ _id: 1, item: 'apple', qty: 5, convertedQty: Long("5") }

注意

変換操作でエラーが発生した場合、集計操作は停止し、エラーがスローされます。この動作をオーバーライドするには、代わりに $convert を使用します。

戻る

$toInt

項目一覧