$log10 - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$log10

4.0 版的新功能。

Amazon DocumentDB 中的$log10運算子用於計算數字的 base-10 對數。它適用於對彙總管道中的數值欄位執行對數計算。

參數

  • expression:計算 base-10 對數的數值表達式。

範例 (MongoDB Shell)

下列範例示範如何使用 $log10運算子來計算數值欄位的 base-10 對數。

建立範例文件

db.numbers.insertMany([ { _id: 1, value: 1 }, { _id: 2, value: 10 }, { _id: 3, value: 100 }, { _id: 4, value: 1000 } ]);

查詢範例

db.numbers.aggregate([ { $project: { _id: 1, log10Value: { $log10: "$value" } } } ]);

輸出

[ { "_id": 1, "log10Value": 0 }, { "_id": 2, "log10Value": 1 }, { "_id": 3, "log10Value": 2 }, { "_id": 4, "log10Value": 3 } ]

程式碼範例

若要檢視使用 $log10命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { let client; try { client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('numbers'); const result = await collection.aggregate([ { $project: { _id: 1, log10Value: { $log10: "$value" } } } ]).toArray(); console.log(result); } catch (error) { console.error("An error occurred:", error); } finally { if (client) { await client.close(); } } } example();
Python
from pymongo import MongoClient def example(): client = None try: client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client.test collection = db.numbers result = list(collection.aggregate([ { '$project': { '_id': 1, 'log10Value': { '$log10': '$value' } } } ])) print(result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()