登录
首页 >  Golang >  Go问答

在 MongoDB 中用 Golang 存储 UUID 的方法

来源:stackoverflow

时间:2024-03-22 08:06:40 346浏览 收藏

在 MongoDB 中使用 Golang 存储 UUID 时,UUID 会被转换为子类型 0 的 Base64 二进制文件,导致无法通过 UUID 查询文档字段。为了解决此问题,可以使用自定义编码器和解码器函数,将 UUID 直接存储为 Mongo 的 BSON 二进制格式,避免转换为 Base64 格式。

问题内容

当使用 golang 在 mongodb 中存储 github.com/google/uuid uuid 字段时,它会转换为子类型 0 的 base64 二进制文件。这使得无法通过 uuid 自然查询文档字段。

插入的用户如下所示:

{"_id":{"$binary":"0bhyonwstv+kqwsl54ywiq==","$type":"0"},"name":"isabella"}

通过生成的uuid d1b1d8a0-d592-4d5f-8aa9-64a5e7861689 查询时,结果为空。

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
}

解决方案


由于 github.com/google/uuid UUID 类型的性质是 [16]byte 的别名,Mongo 将其存储为子类型 0x00 的 BSON 二进制文件。尝试将 UUID 转换为 BSON 的 Base64 二进制格式是不切实际的。因此,您可以选择使用我编写的编码器和解码器功能,该功能可以直接插入此处的 mongo 客户端结构中:https://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 MongoDB 中用 Golang 存储 UUID 的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>