-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
-
Labels:None
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.
- is related to
-
GODRIVER-830 Add support for mongodb UUID type
- Closed
-
GODRIVER-860 Document using UUIDs in mongo as _id's.
- Closed