本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$toInt
4.0 版的新功能
Amazon DocumentDB 中的$toInt運算子用於將輸入值轉換為整數資料類型。當您需要確保欄位或表達式以整數表示時,此運算子很有用,這對於某些操作或資料處理任務至關重要。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $toInt運算子將字串值轉換為整數。
建立範例文件
db.numbers.insertMany([
{ "name": "one", "value": "1" },
{ "name": "hundred", "value": "100" }
]);
查詢範例
db.numbers.aggregate([
{ $project: {
"_id": 0,
"name": 1,
"intValue": { $toInt: "$value" }
}}
]);
輸出
{ "name": "one", "intValue": 1 }
{ "name": "hundred", "intValue": 100 }
程式碼範例
若要檢視使用 $toInt命令的程式碼範例,請選擇您要使用的語言標籤:
- 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');
const db = client.db('test');
const collection = db.collection('numbers');
const result = await collection.aggregate([
{ $project: {
"_id": 0,
"name": 1,
"intValue": { $toInt: "$value" }
}}
]).toArray();
console.log(result);
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')
db = client['test']
collection = db['numbers']
result = list(collection.aggregate([
{ "$project": {
"_id": 0,
"name": 1,
"intValue": { "$toInt": "$value" }
}}
]))
print(result)
client.close()
example()