本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$sqrt
4.0 版的新功能。
Amazon DocumentDB 中的$sqrt運算子用於計算數字的平方根。
參數
範例 (MongoDB Shell)
下列範例示範運算$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()