View a markdown version of this page

$round - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$round

8.0.1 版的新功能。

Amazon 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都會四捨五入到最接近的偶數值 12,而 會13.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()