本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$toDecimal
4.0 版的新功能
Amazon DocumentDB 中的$toDecimal運算子用於將值轉換為 Decimal128 資料類型。當您需要執行精確的小數算法或處理使用 Double 資料類型無法準確表示的大型小數值時,此功能非常有用。
參數
範例 (MongoDB Shell)
此範例示範如何使用 $toDecimal運算子將字串值轉換為 Decimal128 資料類型。
建立範例文件
db.numbers.insertOne({ _id: 1, value: "3.14" });
db.numbers.insertOne({ _id: 2, value: "2.71" });
查詢範例
db.numbers.aggregate([
{ $project: {
_id: 1,
decimalValue: { $toDecimal: "$value" }
}}
])
輸出
[
{ "_id" : 1, "decimalValue" : Decimal128("3.14") },
{ "_id" : 2, "decimalValue" : Decimal128("2.71") }
]
程式碼範例
若要檢視使用 $toDecimal命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('numbers');
const result = await collection.aggregate([
{ $project: {
_id: 1,
decimalValue: { $toDecimal: "$value" }
}}
]).toArray();
console.log(result);
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')
db = client.test
collection = db.numbers
result = list(collection.aggregate([
{'$project': {
'_id': 1,
'decimalValue': {'$toDecimal': '$value'}
}}
]))
print(result)
client.close()
example()