$trunc (aggregation)
定義
$trunc
$trunc
truncates a number to a whole integer or to a specified decimal place.
構文
$trunc
演算子の構文は次のとおりです。
{ $trunc : [ <number>, <place> ] }
フィールド | タイプ | 説明 |
---|---|---|
| 数値 | |
| integer | 任意 Can be any valid 式
that resolves to an integer between -20 and 100, exclusive. For example,
|
<number>
式は、数値に変換される限り、どのような有効な式でもかまいません。 式の詳細については、「式演算子 」を参照してください。
動作
$trunc
does not round the truncated data. To round
input values to a specified place, use the
$round
expression.
Returned Data Type
The returned data type matches the data type of the input expression or value.
null
、NaN
、+/- Infinity
If the argument resolves to a value of
null
or refers to a field that is missing,$trunc
returnsnull
.If the argument resolves to
NaN
,$trunc
returnsNaN
.If the argument resolves to negative or positive infinity,
$trunc
returns negative or positive infinity respectively.
例 | 結果 |
---|---|
|
|
|
|
|
|
|
|
例
次のドキュメントを含むsamples
という名前のコレクションを作成します。
db.samples.insertMany( [ { _id: 1, value: 19.25 }, { _id: 2, value: 28.73 }, { _id: 3, value: 34.32 }, { _id: 4, value: -45.34 } ] )
The following aggregation returns
value
truncated to the first decimal place:db.samples.aggregate([ { $project: { truncatedValue: { $trunc: [ "$value", 1 ] } } } ]) この操作は次の結果を返します。
{ "_id" : 1, "truncatedValue" : 19.2 } { "_id" : 2, "truncatedValue" : 28.7 } { "_id" : 3, "truncatedValue" : 34.3 } { "_id" : 4, "truncatedValue" : -45.3 } The following aggregation returns
value
truncated to the first place:db.samples.aggregate([ { $project: { truncatedValue: { $trunc: [ "$value", -1 ] } } } ]) この操作は次の結果を返します。
{ "_id" : 1, "truncatedValue" : 10 } { "_id" : 2, "truncatedValue" : 20 } { "_id" : 3, "truncatedValue" : 30 } { "_id" : 4, "truncatedValue" : -40 } The following aggregation returns``value`` truncated to the whole integer:
db.samples.aggregate([ { $project: { truncatedValue: { $trunc: [ "$value", 0 ] } } } ]) この操作は次の結果を返します。
{ "_id" : 1, "truncatedValue" : 19 } { "_id" : 2, "truncatedValue" : 28 } { "_id" : 3, "truncatedValue" : 34 } { "_id" : 4, "truncatedValue" : -45 }