View a markdown version of this page

$trunc - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$trunc

버전 8.0.1에서 새로 추가되었습니다.

Amazon DocumentDB의 $trunc 연산자는 숫자를 지정된 소수점 자리로 잘라내어 반올림 없이 숫자를 제거합니다.

파라미터

  • number: 숫자로 확인되는 표현식입니다.

  • place: 선택 사항입니다. 잘라낼 소수 자릿수를 지정하는 -20~100 사이의 정수 표현식입니다. 음수 값은 소수점 왼쪽으로 잘립니다. 기본값은 0입니다.

예제(MongoDB 쉘)

다음 예제에서는 $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가 음수인 경우는 소수점 왼쪽의 숫자를 0으로 $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()