[GODRIVER-2484] Add a Go type for the UUID BSON binary subtype Created: 06/Jul/22  Updated: 28/Mar/23

Status: Backlog
Project: Go Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Unknown
Reporter: Matt Dale Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to GODRIVER-830 Add support for mongodb UUID type Closed
is related to GODRIVER-860 Document using UUIDs in mongo as _id's. Closed

 Description   

There is a lot of interest in using UUIDs in MongoDB documents, specifically as the _id field. However, using UUIDs with the Go Driver currently is not a great experience because UUIDs are converted to a generic binary representation by default. Add a UUID type to the Go Driver BSON library to make it easier to encode, decode, and query with UUID values.

Note that the github.com/google/uuid library seems to be the most popular UUID library for Go, so make sure interoperability with that library is simple and well-documented. Other popular Go UUID libraries include github.com/satori/go.uuid and github.com/gofrs/uuid.

Consider defining the UUID type as a [16]byte, which matches the type defined in the google/uuid library:

type UUID [16]byte

It's not clear if implementing a primitive.UUID type would be backward-breaking or not. If so, this would have to be implemented with the v2.0 Go Driver.

Use Cases

All use cases use the uuid.UUID type from the github.com/google/uuid package.

Use case 1: Insert UUID.

var id uuid.UUID = uuid.New()
coll.InsertOne(context.TODO(), bson.D{{"_id", primitive.UUID(id)}})
// Expect that the "_id" field in the inserted document is BSON type "binary" with subtype 4 (UUID).

Use case 2: Decode UUID.

var res bson.M
coll.FindOne(context.TODO(), bson.D{}).Decode(&res)
fmt.Println(res)
// Expect that any values with BSON type "binary" with subtype 4 (UUID) are printed as UUID string values (e.g. "64ab9f79-1808-48fb-834b-97ee4e1e73f7"), not as {{primitive.Binary}} values.

Use case 3: Query with UUID.

var id uuid.UUID
var res bson.M
coll.FindOne(context.TODO(), bson.M{"_id": primitive.UUID(id)}).Decode(&res)
fmt.Println(res)
// Expect that we can find the document inserted in Use case 1 with the same "_id" value.



 Comments   
Comment by Dorian Heinrichs [ 28/Mar/23 ]

Is there any update on when this will be implemented and available to use? I need to use UUID for an _id and I cannot really figure out a way to use it. 

Comment by Benji Rewis (Inactive) [ 08/Aug/22 ]

We'll want to document how to use this new UUID type and the existing primitive.ObjectID type somewhere public-facing per GODRIVER-860.

Generated at Thu Feb 08 08:38:44 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.