SupaHam
SupaHam

Reputation: 1225

How to store a UUID in MongoDB with Golang?

When storing a github.com/google/uuid UUID field in MongoDB using Golang it translates to a base64 binary with subtype 0. This makes it impossible to naturally query the document field by UUID.

The inserted user looks like:

{"_id":{"$binary":"0bHYoNWSTV+KqWSl54YWiQ==","$type":"0"},"name":"Isabella"}

When querying by the generated UUID d1b1d8a0-d592-4d5f-8aa9-64a5e7861689, the results are empty.

type User struct {
    UserId uuid.UUID `json:"userId" bson:"_id"`
    Name   string    `json:"name" bson:"name"`
}

func (repo userRepo) User(uuidIn uuid.UUID) (model.User, error) {
    collection := repo.database.Collection(mongoCollectionUser)
    var user model.User
    err := collection.FindOne(context.Background(),
        bson.M{"_id": uuidIn},
    ).Decode(&user)
    // err: mongo: no documents in result
}

Upvotes: 7

Views: 5535

Answers (1)

SupaHam
SupaHam

Reputation: 1225

Due to the nature of github.com/google/uuid UUID type being an alias of [16]byte, Mongo will resort to storing it as a BSON Binary of subtype 0x00. It is impractical to attempt to convert the UUID to a base64 binary format for BSON. So you may choose to use this encoder & decoder feature I wrote that can be plugged directly into the mongo client struct here: https://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77

Upvotes: 7

Related Questions