$toDouble - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$toDouble

Baru dari versi 4.0

$toDoubleOperator di Amazon DocumentDB digunakan untuk mengonversi nilai menjadi nomor floating-point 64-bit presisi ganda. Ini dapat berguna ketika Anda perlu melakukan operasi aritmatika pada nilai-nilai yang awalnya tidak dalam format numerik.

Parameter

<expression>: Ekspresi untuk mengkonversi ke nilai ganda. Ini bisa berupa ekspresi valid yang menyelesaikan nilai numerik, string, atau boolean.

Contoh (MongoDB Shell)

Contoh ini menunjukkan bagaimana menggunakan $toDouble operator untuk mengkonversi nilai string ke nilai numerik untuk tujuan melakukan perhitungan matematis.

Buat dokumen sampel

db.numbers.insertMany([ { _id: 1, value: "10.5" }, { _id: 2, value: "20.25" }, { _id: 3, value: "7" } ])

Contoh kueri

db.numbers.aggregate([ { $project: { _id: 1, value: 1, double_value: { $toDouble: "$value" }, double_plus_five: { $add: [{ $toDouble: "$value" }, 5] } } } ])

Keluaran

[ { "_id" : 1, "value" : "10.5", "double_value" : 10.5, "double_plus_five" : 15.5 }, { "_id" : 2, "value" : "20.25", "double_value" : 20.25, "double_plus_five" : 25.25 }, { "_id" : 3, "value" : "7", "double_value" : 7.0, "double_plus_five" : 12.0 } ]

Contoh kode

Untuk melihat contoh kode untuk menggunakan $toDouble perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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, value: 1, double_value: { $toDouble: "$value" }, double_plus_five: { $add: [{ $toDouble: "$value" }, 5] } } } ]).toArray(); console.log(result); 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') db = client['test'] collection = db['numbers'] result = list(collection.aggregate([ { '$project': { '_id': 1, 'value': 1, 'double_value': { '$toDouble': '$value' }, 'double_plus_five': { '$add': [{ '$toDouble': '$value' }, 5] } } } ])) print(result) client.close() example()