For AI agents: a documentation index is available at https://www.mongodb.com/zh-cn/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

$toUUID (expression operator)

New in version 8.0.

$toUUID

Converts a string value to a UUID. If the input value is not a string, $toUUID errors.

{ $toUUID: <expression>}

The $toUUID expression is shorthand for the following $convert expression:

{ $convert: { input: <expression>, to: { type: "binData", subtype: 4 // UUID }, format: "uuid" }}

Create a products collection with the following document:

db.products.insertOne( { name: "laptop", price: 400, UUID: "0e3b9063-8abd-4eb3-9f9f-f4c59fd30a60" })

In the example document, the UUID field is a string. To convert the UUID field to a UUID value, run the following $toUUID operation:

db.products.aggregate( [ { $project: { name: 1, price: 1, UUID: { $toUUID: "$UUID" } } }] )

Output:

[ { _id: ObjectId('669945ab610b080391a8e2f5'), name: 'laptop', price: 400, UUID: UUID('0e3b9063-8abd-4eb3-9f9f-f4c59fd30a60') }]
Rate this page