You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang中如何将MongoDB SessionID字符串转换为bson.Raw格式

问题

在Golang项目中连接MongoDB并开启会话后,已通过session1.ID()获取到bson.Raw类型的SessionID,调用其String()方法得到字符串变量ass,现需将ass转换回bson.Raw格式。相关代码及依赖配置如下:

业务代码

func main() {
    uri := "mongodb://root:cc@172.22.50.25:32082,172.22.50.25:32083,172.22.50.25:32084/?connectTimeoutMS=300000&authSource=admin"
    opt := options.Client().ApplyURI(uri).SetSocketTimeout(timeout)

    ctx, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()

    client, err := mongo.Connect(ctx, opt)
    if err != nil {
        logs.Error("connect mongo failed, err:%s", err.Error())
        return
    }

    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        logs.Error("ping mongo failed, err:%s", err.Error())
        return
    }

    wc := writeconcern.New(writeconcern.WMajority())
    rc := readconcern.Snapshot()

    var maxCommitTime = time.Second * 10

    sessionOpts := &options.SessionOptions{}
    sessionOpts.SetDefaultWriteConcern(wc).SetDefaultReadConcern(rc).SetDefaultMaxCommitTime(&maxCommitTime)

    session1, _ := client.StartSession(sessionOpts)
    sessionContext := mongo.NewSessionContext(ctx, session1)
    if err := sessionContext.StartTransaction(); err != nil {
        panic(err)
    }

    // Transaction-based crud
    txn(client, session1, sessionContext, ctx)
    as := session1.ID() // bson.raw 
    fmt.Println(as.String())
    ass := as.String() // How to convert ass string variable to bson.raw
        ???       
}

go.mod配置

go 1.16

require (
    github.com/google/uuid v1.2.0
    go.mongodb.org/mongo-driver v1.10.6
)

解决方案

MongoDB会话ID的字符串格式为标准UUID(session1.ID()本质是UUID类型,被序列化为bson.Raw),转换需分两步完成:

  1. 将字符串ass解析为uuid.UUID类型
  2. 将uuid.UUID序列化为bson.Raw

具体实现代码如下:

import (
    "github.com/google/uuid"
    "go.mongodb.org/mongo-driver/bson"
)

// ... 原有业务代码 ...

ass := as.String()

// 解析字符串为UUID
uuidVal, err := uuid.Parse(ass)
if err != nil {
    logs.Error("parse session id string failed, err:%s", err.Error())
    return
}

// 将UUID序列化为bson.Raw
rawSessionID, err := bson.Marshal(uuidVal)
if err != nil {
    logs.Error("marshal uuid to bson.Raw failed, err:%s", err.Error())
    return
}

// rawSessionID即为转换后的bson.Raw类型,可验证与原session1.ID()输出一致
fmt.Println(rawSessionID.String())

补充说明

  • MongoDB会话ID底层存储为UUID,bson.Raw保存的是UUID的BSON二进制表示
  • 使用bson.Marshal转换得到的bson.Raw,与session1.ID()返回的格式完全匹配
  • 解析时需确保输入字符串为有效UUID格式,否则会返回错误

内容的提问来源于stack exchange,提问作者Jun Tao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:00:28