Skip to content

Instantly share code, notes, and snippets.

@fracasula
Created February 15, 2022 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fracasula/795ea50489f9d03ef41c2e5973b344c1 to your computer and use it in GitHub Desktop.
Save fracasula/795ea50489f9d03ef41c2e5973b344c1 to your computer and use it in GitHub Desktop.
Golang MongoDB UUID
package mongouuid
import (
"fmt"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
type UUID struct {
data uuid.UUID
}
func (u *UUID) String() string {
return u.data.String()
}
func (u UUID) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bsontype.Binary, bsoncore.AppendBinary(nil, bsontype.BinaryUUID, u.data[:]), nil
}
func (u *UUID) UnmarshalBSONValue(t bsontype.Type, raw []byte) error {
if t != bsontype.Binary {
return fmt.Errorf("expected Binary type, got %+v", t)
}
subtype, data, _, ok := bsoncore.ReadBinary(raw)
if !ok {
return fmt.Errorf("not enough bytes to unmarshal bson value")
}
if subtype != bsontype.BinaryUUID {
return fmt.Errorf("expected UUID subtype, got %+v", t)
}
var err error
u.data, err = uuid.FromBytes(data)
return err
}
func FromString(str string) (v UUID, err error) {
v.data, err = uuid.Parse(str)
return
}
func FromBytes(b []byte) (v UUID, err error) {
v.data, err = uuid.FromBytes(b)
return
}
@fracasula
Copy link
Author

fracasula commented Feb 15, 2022

Thanks to the right subtype (i.e. 0x04, see bsontype.BinaryUUID), now it shows correctly from the command line as well:

Screenshot from 2022-02-15 14-00-55

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment