文档菜单
文档首页
/
MongoDB 手册
/ / /

$round (聚合)

本页内容

  • 定义
  • 行为
  • 示例
$round

$round 将数字四舍五入到整数或指定的小数位数。

$round 的语法如下

{ $round : [ <number>, <place> ] }
字段
类型
描述
<number>
数字

可以是任何有效的表达式,该表达式解析为数字。具体来说,表达式必须解析为整数、双精度浮点数、decimallong.

$round 如果表达式解析为非数值数据类型,则返回错误。

<place>
整数

可选 可以是任何有效的 表达式,该表达式解析为介于 -20 和 100 之间的整数(不包括 100)。例如,-20 < place < 100。如果未指定,则默认为 0

  • 如果 <place> 解析为正整数,则 $round 将四舍五入到 <place> 小数位。

    例如,$round : [1234.5678, 2] 四舍五入到两位小数,并返回 1234.57

  • 如果 <place> 解析为负整数,则 $round 使用小数点左侧的 <place> 位数字进行四舍五入。

    例如,$round : [1234.5678, -2] 使用小数点左侧的第 2 位数字(3)并返回 1200

    如果 <place> 的绝对值等于或超过小数点左侧的数字位数,则 $round 返回 0

    例如,$round : [ 1234.5678, -4] 指定小数点左边的第四位。这等于小数点左边的数字位数,并返回 0

  • 如果 <place> 解析为 0,则 $round 使用小数点右边第一个数字进行四舍五入,并返回四舍五入的整数值。

    例如,$round : [1234.5678, 0] 返回 1235

当对值为 5 的值进行四舍五入时,$round 会四舍五入到最近的偶数值。例如,考虑以下示例文档

{_id : 1, "value" : 10.5},
{_id : 2, "value" : 11.5},
{_id : 3, "value" : 12.5},
{_id : 4, "value" : 13.5}

$round : [ "$value", 0] 返回以下内容

{_id : 1, "value" : 10},
{_id : 2, "value" : 12},
{_id : 3, "value" : 12},
{_id : 4, "value" : 14}

10.5 最接近偶数值 10,而值 11.512.5 最接近偶数值 12。四舍五入到最近的偶数值比总是向上或向下四舍五入支持更均匀的舍入数据分布。

返回的数据类型与输入表达式或值的类型匹配。

  • 如果第一个参数解析为 null 或引用了一个缺失的字段,$round 返回 null

  • 如果第一个参数解析为 NaN$round 返回 NaN

  • 如果第一个参数解析为负无穷大或正无穷大,$round 分别返回负无穷大或正无穷大。

示例
结果
{ $round: [ NaN, 1] }
NaN
{ $round: [ null, 1] }
null
{ $round : [ Infinity, 1 ] }
Infinity
{ $round : [ -Infinity, 1 ] }
-Infinity

创建一个名为 samples 的集合,包含以下文档

db.samples.insertMany(
[
{ _id: 1, value: 19.25 },
{ _id: 2, value: 28.73 },
{ _id: 3, value: 34.32 },
{ _id: 4, value: -45.39 }
]
)
  • 以下聚合操作返回四舍五入到小数点后一位的 value

    db.samples.aggregate([
    { $project: { roundedValue: { $round: [ "$value", 1 ] } } }
    ])

    此操作返回以下结果

    { "_id" : 1, "roundedValue" : 19.2 }
    { "_id" : 2, "roundedValue" : 28.7 }
    { "_id" : 3, "roundedValue" : 34.3 }
    { "_id" : 4, "roundedValue" : -45.4 }
  • 以下聚合操作返回使用小数点左边第一个数字进行四舍五入的 value

    db.samples.aggregate([
    { $project: { roundedValue: { $round: [ "$value", -1 ] } } }
    ])

    此操作返回以下结果

    { "_id" : 1, "roundedValue" : 10 }
    { "_id" : 2, "roundedValue" : 20 }
    { "_id" : 3, "roundedValue" : 30 }
    { "_id" : 4, "roundedValue" : -50 }
  • 以下聚合操作返回四舍五入到整数的 value

    db.samples.aggregate([
    { $project: { roundedValue: { $round: [ "$value", 0 ] } } }
    ])

    此操作返回以下结果

    { "_id" : 1, "roundedValue" : 19 }
    { "_id" : 2, "roundedValue" : 29 }
    { "_id" : 3, "roundedValue" : 34 }
    { "_id" : 4, "roundedValue" : -45 }

返回

$reverseArray

本页内容