기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$sqrt
버전 4.0에서 새로 추가되었습니다.
Amazon DocumentDB의 $sqrt 연산자는 숫자의 제곱근을 계산하는 데 사용됩니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 $sqrt 연산자를 사용하여 숫자의 제곱근을 계산하는 방법을 보여줍니다.
샘플 문서 생성
db.numbers.insertMany([
{ "_id": 1, "number": 16 },
{ "_id": 2, "number": 36 },
{ "_id": 3, "number": 64 }
]);
쿼리 예제
db.numbers.aggregate([
{ $project: {
"_id": 1,
"square_root": { $sqrt: "$number" }
}}
]);
출력
[
{ _id: 1, square_root: 4 },
{ _id: 2, square_root: 6 },
{ _id: 3, square_root: 8 }
]
코드 예제
$sqrt 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.
- 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');
try {
await client.connect();
const db = client.db('test');
const collection = db.collection('numbers');
const pipeline = [
{
$project: {
_id: 1,
square_root: { $sqrt: '$number' }
}
}
];
const results = await collection.aggregate(pipeline).toArray();
console.dir(results, { depth: null });
} finally {
await client.close();
}
}
example().catch(console.error);
- 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.numbers
pipeline = [
{
"$project": {
"_id": 1,
"square_root": {
"$sqrt": "$number"
}
}
}
]
results = collection.aggregate(pipeline)
for doc in results:
print(doc)
except Exception as e:
print(f"An error occurred: {e}")
finally:
client.close()
example()