View a markdown version of this page

$trunc - Amazon DocumentDB

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

$trunc

バージョン 8.0.1 から新規。

Amazon DocumentDB の $trunc演算子は、数値を指定した小数点以下を切り捨て、四捨五入せずに桁を削除します。

パラメータ

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

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

例 (MongoDB シェル)

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

正のプレース値で切り捨てる

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

クエリの例

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

出力

[ {_id: 1, truncated: 3.4}, {_id: 2, truncated: 7.8}, {_id: 3, truncated: 12.3} ]

負のプレース値で切り捨てる

place が負の場合、 $trunc は 10 進数の左にある数字をゼロに置き換えます。次の例では、10 進数の左にある最初の桁を使用して値を切り捨てます。

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

出力

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

コードの例

$trunc 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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: { truncated: { $trunc: ["$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': {'truncated': {'$trunc': ['$value', 1]}}} ])) print(result) finally: client.close() example()