View a markdown version of this page

$trunc - Amazon DocumentDB

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

$trunc

8.0.1 版中的新增内容。

Amazon DocumentDB 中的$trunc运算符将数字截断为指定的小数位,删除数字时不进行四舍五入。

参数

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

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

示例(MongoDB Shell)

以下示例说明如何使用$trunc运算符将数值截断到小数点后一位。

用正的位值截断

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将小数点左边的数字替换为零。以下示例使用十进制左边的第一位数字截断值。

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