On this page本页内容
$trunc
Changed in version 4.2..在版本4.2.中更改。
$trunc
truncates a number to a whole integer or to a specified decimal place.将数字截断为整数或指定的小数位。
MongoDB 4.2 adds the following syntax for MongoDB 4.2为$trunc
:$trunc
添加了以下语法:
{ $trunc : [ <number>, <place> ] }
<number> | number |
|
<place> | integer |
|
Prior to MongoDB 4.2, 在MongoDB 4.2之前,$trunc
truncated the input value to the whole integer. $trunc
将输入值截断为整数。MongoDB 4.2 continues supporting the pre-4.2 syntax and behavior:MongoDB 4.2继续支持4.2之前的语法和行为:
{ $trunc: <number> }
The <number>
expression can be any valid expression as long as it resolves to a number. <number>
表达式可以是任何有效的表达式,只要它解析为数字。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
$trunc
does not round the truncated data. 不舍入截断的数据。To round input values to a specified place, use the 要将输入值舍入到指定位置,请使用$round
expression.$round
表达式。
If truncating to a specific decimal place, the data type returned by 如果截断到特定的小数位,$trunc
matches the data type of the input expression or value.$trunc
返回的数据类型将与输入表达式或值的数据类型匹配。
If truncating to a whole integer value, 如果截断为整数值,$trunc
returns an integer.$trunc
将返回一个整数。
null
, NaN
, and +/- Infinity
null
or refers to a field that is missing, $trunc
returns null
.null
值或引用缺少的字段,$trunc
将返回null
。NaN
, $trunc
returns NaN
.NaN
,$trunc
将返回NaN
。$trunc
returns negative or positive infinity respectively.$trunc
将分别返回负无穷大和正无穷大。{ $trunc: [ NaN, 1] } | NaN |
{ $trunc: [ null, 1] } | null |
{ $trunc : [ Infinity, 1 ] } | Infinity |
{ $trunc : [ -Infinity, 1 ] } | -Infinity |
A collection named 名为samples
contains the following documents:samples
的集合包含以下文档:
{ _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:value
:
db.samples.aggregate([ { $project: { truncatedValue: { $trunc: [ "$value", 1 ] } } } ])
The operation returns the following results:该操作返回以下结果:
{ "_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:value
:
db.samples.aggregate([ { $project: { truncatedValue: { $trunc: [ "$value", -1 ] } } } ])
The operation returns the following results:该操作返回以下结果:
{ "_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:value
:
db.samples.aggregate([ { $project: { truncatedValue: { $trunc: [ "$value", 0 ] } } } ])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "truncatedValue" : 19 } { "_id" : 2, "truncatedValue" : 28 } { "_id" : 3, "truncatedValue" : 34 } { "_id" : 4, "truncatedValue" : -45 }