View a markdown version of this page

$round - Amazon DocumentDB

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

$round

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

Amazon DocumentDB의 $round 연산자는 숫자를 지정된 소수점 자리로 반올림합니다. 값이 해당 위치에서 가장 가까운 두 값 사이의 정확히 중간에 있는 경우는 가장 가까운 짝수로 $round 반올림합니다. 예를 들어 2.5는 2로, 3.5는 4로 반올림합니다.

파라미터

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

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

예제(MongoDB 쉘)

다음 예제에서는 $round 연산자를 사용하여 숫자 값을 소수점 한 자리로 반올림하는 방법을 보여줍니다.

양수 자리 값으로 반올림

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

쿼리 예제

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

출력

[ {_id: 1, rounded: 3.5}, {_id: 2, rounded: 7.9}, {_id: 3, rounded: 12.3} ]

반원 값을 가장 가까운 짝수로 반올림

값이 대상 위치에서 가장 가까운 두 값 사이의 정확히 중간에 있는 경우는 항상 $round 반올림하는 대신 가장 가까운 짝수로 반올림합니다. 다음 예제에서는 반원 값을 정수로 반올림합니다.

db.halfway.insertMany([ {_id: 1, value: 10.5}, {_id: 2, value: 11.5}, {_id: 3, value: 12.5}, {_id: 4, value: 13.5} ]);
db.halfway.aggregate([ { $project: { rounded: { $round: ["$value", 0] } } } ]);

출력

[ {_id: 1, rounded: 10}, {_id: 2, rounded: 12}, {_id: 3, rounded: 12}, {_id: 4, rounded: 14} ]

10.510와의 정확히 중간에 11있기 때문에 가장 가까운 짝수 값 로 반올림됩니다10. 마찬가지로 11.5 및는 12.5 모두 가장 가까운 짝수 값 로 반올림하고 12는 로 13.5 반올림합니다14.

음수 자리 값으로 반올림

place가 음수이면 소수점 왼쪽으로 $round 반올림합니다. 다음 예제에서는 첫 번째 숫자를 소수점 왼쪽으로 사용하여 값을 반올림합니다.

db.samples.insertMany([ {_id: 1, value: 19.25}, {_id: 2, value: 28.73}, {_id: 3, value: 34.32} ]);
db.samples.aggregate([ { $project: { rounded: { $round: ["$value", -1] } } } ]);

출력

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

코드 예제

$round 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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: { rounded: { $round: ["$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': {'rounded': {'$round': ['$value', 1]}}} ])) print(result) finally: client.close() example()