Definition定义
$trunc$trunctruncates a number to a whole integer or to a specified decimal place.将数字截断为整数或指定的小数位。
Syntax语法
The $trunc operator has the following syntax:$trunc运算符具有以下语法:
{ $trunc : [ <number>, <place> ] }
<number> |
| |
<place> |
|
The <number> expression can be any valid expression as long as it resolves to a number. <number>表达式可以是任何有效的表达式,只要它解析为数字。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
$trunc does not round the truncated data. To round input values to a specified place, use the $round expression.$trunc不会对截断的数据进行四舍五入。要将输入值四舍五入到指定位置,请使用$round表达式。
Returned Data Type返回的数据类型
The returned data type matches the data type of the input expression or value.返回的数据类型与输入表达式或值的数据类型匹配。
null, NaN, and +/- Infinity
If the argument resolves to a value of如果参数解析为nullor refers to a field that is missing,$truncreturnsnull.null值或引用缺少的字段,$trunc将返回null。If the argument resolves to如果参数解析为NaN,$truncreturnsNaN.NaN,$trunc将返回NaN。If the argument resolves to negative or positive infinity,如果参数解析为负无穷大或正无穷大,$truncreturns negative or positive infinity respectively.$trunc将分别返回负无穷大和正无穷大。
{ $trunc: [ NaN, 1] } | NaN |
{ $trunc: [ null, 1] } | null |
{ $trunc : [ Infinity, 1 ] } | Infinity |
{ $trunc : [ -Infinity, 1 ] } | -Infinity |
Example示例
Create a collection named 使用以下文档创建一个名为samples with the following documents: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以下聚合返回截断到第一位小数的valuetruncated 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以下聚合返回截断到第一位的valuetruncated 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以下聚合返回截断为整数的valuetruncated 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 }