On this page本页内容
$round
New in version 4.2..在版本4.2.中新增。
$round rounds a number to a whole integer or to a specified decimal place.将数字四舍五入为整数或指定的小数位。
$round has the following syntax:语法如下:
{ $round : [ <number>, <place> ] }
<number> | number |
|
<place> | integer |
|
When rounding on a value of 当舍入值为5, $round rounds to the nearest even value. 5时,$round将舍入到最接近的偶数值。For example, consider the following sample documents:例如,考虑以下示例文档:
{_id : 1, "value" : 10.5},
{_id : 2, "value" : 11.5},
{_id : 3, "value" : 12.5},
{_id : 4, "value" : 13.5}
$round : [ "$value", 0] returns the following:返回以下内容:
{_id : 1, "value" : 10},
{_id : 2, "value" : 12},
{_id : 3, "value" : 12},
{_id : 4, "value" : 14}
The value 值10.5 is closest to the even value 10, while the values 11.5 and 12.5 are closest to the even value 12. 10.5最接近偶数值10,而值11.5和12.5最接近偶数值12。Rounding to the nearest even value supports more even distribution of rounded data than always rounding up or down.舍入到最接近的偶数值比总是向上或向下舍入支持更均匀的舍入数据分布。
If rounding to a specific decimal place, the data type returned by 如果舍入到特定的小数位,$round matches the data type of the input expression or value.$round返回的数据类型将与输入表达式或值的数据类型匹配。
If rounding to a whole integer value, 如果舍入为整数值,$round returns the value as an integer.$round将返回整数值。
null, NaN, and +/- Infinitynull or refers to a field that is missing, $round returns null.null值或引用缺少的字段,$round将返回null。NaN, $round returns NaN.$round返回NaN。$round returns negative or positive infinity respectively.$round将分别返回负无穷大和正无穷大。{ $round: [ NaN, 1] } | NaN |
{ $round: [ null, 1] } | null |
{ $round : [ Infinity, 1 ] } | Infinity |
{ $round : [ -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.39 }
The following aggregation returns 以下聚合返回四舍五入到第一个小数位的value rounded to the first decimal place:value:
db.samples.aggregate([
{ $project: { roundedValue: { $round: [ "$value", 1 ] } } }
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "roundedValue" : 19.2 }
{ "_id" : 2, "roundedValue" : 28.7 }
{ "_id" : 3, "roundedValue" : 34.3 }
{ "_id" : 4, "roundedValue" : -45.4 }
The following aggregation returns 以下聚合将返回使用小数点左边第一位四舍五入的value rounded using the first digit to the left of the decimal:value:
db.samples.aggregate([
{ $project: { roundedValue: { $round: [ "$value", -1 ] } } }
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "roundedValue" : 10 }
{ "_id" : 2, "roundedValue" : 20 }
{ "_id" : 3, "roundedValue" : 30 }
{ "_id" : 4, "roundedValue" : -50 }
The following aggregation returns 以下聚合返回四舍五入到整数的value rounded to the whole integer:value:
db.samples.aggregate([
{ $project: { roundedValue: { $round: [ "$value", 0 ] } } }
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "roundedValue" : 19 }
{ "_id" : 2, "roundedValue" : 29 }
{ "_id" : 3, "roundedValue" : 34 }
{ "_id" : 4, "roundedValue" : -45 }