本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$toUUID
8.0.1 版的新功能。
Amazon DocumentDB 中的$toUUID運算子會將字串值轉換為 UUID (二進位子類型 4)。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $toUUID運算子將字串值轉換為 UUID 格式。
建立範例文件
db.records.insertMany([
{_id: 1, uuidStr: "550e8400-e29b-41d4-a716-446655440000"},
{_id: 2, uuidStr: "6ba7b810-9dad-11d1-80b4-00c04fd430c8"}
]);
查詢範例
db.records.aggregate([
{ $project: { uuid: { $toUUID: "$uuidStr" } } }
]);
輸出
[
{_id: 1, uuid: UUID("550e8400-e29b-41d4-a716-446655440000")},
{_id: 2, uuid: UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8")}
]
程式碼範例
若要檢視使用 $toUUID 運算子的程式碼範例,請選擇您要使用的語言標籤:
- 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('records');
const result = await collection.aggregate([
{ $project: { uuid: { $toUUID: "$uuidStr" } } }
]).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['records']
result = list(collection.aggregate([
{'$project': {'uuid': {'$toUUID': '$uuidStr'}}}
]))
print(result)
finally:
client.close()
example()