View a markdown version of this page

$trunc - Amazon DocumentDB

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

$trunc

Baru dari versi 8.0.1.

$truncOperator di Amazon DocumentDB memotong angka ke tempat desimal tertentu, menghapus digit tanpa pembulatan.

Parameter

  • number: Ekspresi yang diselesaikan menjadi angka.

  • place: Opsional. Ekspresi integer antara -20 dan 100 yang menentukan jumlah tempat desimal untuk dipangkas. Nilai negatif dipotong di sebelah kiri desimal. Defaultnya 0.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $trunc operator untuk memotong nilai numerik ke satu tempat desimal.

Memotong dengan nilai tempat positif

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

Contoh kueri

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

Keluaran

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

Memotong dengan nilai tempat negatif

Ketika place negatif, $trunc ganti digit di sebelah kiri desimal dengan nol. Contoh berikut memotong nilai menggunakan digit pertama di sebelah kiri desimal.

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

Keluaran

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

Contoh kode

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

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