View a markdown version of this page

$round - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$round

8.0.1 版中的新增内容。

亚马逊 DocumentDB 中的$round运算符将一个数字四舍五入到指定的小数位数。当一个值恰好落在该位置的两个最接近的值之间时,$round四舍五入到最接近的偶数。例如,2.5 轮到 2,3.5 轮到 4。

参数

  • number:解析为数字的表达式。

  • place:可选。介于 -20 和 100 之间的整数表达式,用于指定要四舍五入的小数位数。负值向小数点的左边四舍五入。默认值为 0。

示例(MongoDB Shell)

以下示例说明如何使用$round运算符将数值四舍五入到小数点后一位。

用正位值四舍五入

db.measurements.insertMany([ {_id: 1, value: 3.456}, {_id: 2, value: 7.891}, {_id: 3, value: 12.345} ]);

查询示例

db.measurements.aggregate([ { $project: { rounded: { $round: ["$value", 1] } } } ]);

输出

[ {_id: 1, rounded: 3.5}, {_id: 2, rounded: 7.9}, {_id: 3, rounded: 12.3} ]

将中间值四舍五入到最接近的偶数

当一个值恰好落在目标位置的两个最接近的值之间时,四$round舍五入到最接近的偶数,而不是总是向上舍入。以下示例将中间值四舍五入为整数。

db.halfway.insertMany([ {_id: 1, value: 10.5}, {_id: 2, value: 11.5}, {_id: 3, value: 12.5}, {_id: 4, value: 13.5} ]);
db.halfway.aggregate([ { $project: { rounded: { $round: ["$value", 0] } } } ]);

输出

[ {_id: 1, rounded: 10}, {_id: 2, rounded: 12}, {_id: 3, rounded: 12}, {_id: 4, rounded: 14} ]

因为10.5正好介于10和之间11,所以四舍五入到最接近的偶数值10。同样11.512.5两者都舍入到最接近的偶数值1213.5四舍五入为14

用负位值四舍五入

place为负数时,向小数点的左边$round四舍五入。以下示例使用小数点左边的第一位数字对值进行四舍五入。

db.samples.insertMany([ {_id: 1, value: 19.25}, {_id: 2, value: 28.73}, {_id: 3, value: 34.32} ]);
db.samples.aggregate([ { $project: { rounded: { $round: ["$value", -1] } } } ]);

输出

[ {_id: 1, rounded: 20}, {_id: 2, rounded: 30}, {_id: 3, rounded: 30} ]

代码示例

要查看使用$round运算符的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('measurements'); const result = await collection.aggregate([ { $project: { rounded: { $round: ["$value", 1] } } } ]).toArray(); console.log(result); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') try: db = client['test'] collection = db['measurements'] result = list(collection.aggregate([ {'$project': {'rounded': {'$round': ['$value', 1]}}} ])) print(result) finally: client.close() example()