View a markdown version of this page

$round - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$round

バージョン 8.0.1 から新規。

Amazon DocumentDB の$round演算子は、数値を指定された小数点以下を切り捨てます。その場所にある 2 つの最も近い値のちょうど中間の値になると、 は最も近い偶数に$round四捨五入します。たとえば、2.5 は 2 に、3.5 は 4 に切り上げられます。

パラメータ

  • number: 数値に解決される式。

  • place: オプション。小数点以下桁数を指定する -20~100 の整数式。負の値は 10 進数の左に丸められます。デフォルトは 0 です。

例 (MongoDB シェル)

次の例は、 $round演算子を使用して数値を小数点以下第 1 位に四捨五入する方法を示しています。

正のプレース値での四捨五入

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} ]

中間値を最も近い偶数に四捨五入する

値がターゲットの場所にある 2 つの最も近い値のちょうど中間になると、 は常に$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.510と のちょうど中間であるため11、最も近い偶数値 に丸められます10。同様に、 11.512.5はどちらも最も近い偶数値 に四捨五入され12、 は に13.5四捨五入されます14

負のプレース値での四捨五入

place が負の場合、 は 10 進数の左に$round丸めます。次の例では、最初の桁を使用して 10 進数の左に値を四捨五入します。

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()