本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$touUID
8.0.1 版中的新增内容。
亚马逊 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()