更新时间:2026-07-21 GMT+08:00
Go示例
操作场景
DDS支持通过Go语言接口来操作数据,通过Go连接实例的方式有开启SSL认证连接和关闭SSL认证连接两种,其中开启SSL证书连接加密功能,具有更高的安全性。
DDS新实例默认关闭SSL数据加密,开启SSL请参考开启SSL。
本章节主要介绍使用Go语言连接副本集实例的方法。
前提条件
环境配置及驱动获取
使用 Go Modules 添加 MongoDB 官方驱动,步骤如下:
- 初始化模块(如尚未创建 go.mod)
go mod init <项目模块名>
- 安装驱动
推荐使用 go get 直接获取指定版本,命令会自动更新 go.mod 与 go.sum:
go get go.mongodb.org/mongo-driver@v1.12.1
若需手动声明依赖,可在 go.mod 中添加:
require go.mongodb.org/mongo-driver v1.12.1
之后执行 go mod tidy 完成下载。
- 在 Go 代码中导入包
import ( "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" )
开启和关闭SSL安全连接
// 高可用连接 readPreference 取值 primary(默认)-只读主节点,primaryPreferred-主节点优先,如主节点不可用,则读从节点
// secondary-只读从节点,如从节点不可用会报错,secondaryPreferred-从节点优先,如从节点不可用,则读主节点
// 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;
// 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
username = System.getenv("EXAMPLE_USERNAME_ENV")
password = System.getenv("EXAMPLE_PASSWORD_ENV")
highProxyUri := fmt.Sprintf("mongodb://%v:%v@host1:8635,host2:8635/?authSource=admin&replicaSet=replica&readPreference=secondaryPreferred",username,password)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOpts := options.Client().ApplyURI(highProxyUri)
client, err := mongo.Connect(ctx, clientOpts)
// Ping 主节点
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()err = client.Ping(ctx, readpref.Primary())
if err != nil {
fmt.Println("ping 主节点失败:",err)
return
}
// 选择数据库和集合
collection := client.Database("test").Collection("numbers")
// 插入单条数据
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}})
if err != nil{
fmt.Println("插入单条记录失败:",err)
return
}else {
fmt.Println(res)
} // 构建认证凭证
// 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;
// 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
username = System.getenv("EXAMPLE_USERNAME_ENV")
password = System.getenv("EXAMPLE_PASSWORD_ENV")
credential := options.Credential{
AuthMechanism: "SCRAM-SHA-1",
AuthSource: "admin",
Username: username,
Password: password,
}
// 高可用 URI, 注意 SetDirect 设为 false
highProxyUri := "mongodb://host1:8635,host2:8635/?ssl=true"
clientOpts := options.Client().ApplyURI(highProxyUri)
clientOpts = clientOpts.SetTLSConfig(&tls.Config {
InsecureSkipVerify: true,
}).SetDirect(false).SetAuth(credential)
// 直连的 URI,注意 SetDirect 设为 true
//directUri := "mongodb://host:8635/?ssl=true"
//clientOpts := options.Client().ApplyURI(highProxyUri)
//clientOpts = clientOpts.SetTLSConfig(&tls.Config {
// InsecureSkipVerify: true,
//}).SetDirect(true).SetAuth(credential)
// 连接实例
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
fmt.Println("mongo实例连接失败:", err)
return
}
// Ping 主节点
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()err = client.Ping(ctx, readpref.Primary())
if err != nil {fmt.Println("ping 主节点失败:",err)
return
}
// 选择数据库和集合
collection := client.Database("test").Collection("numbers")
// 插入单条数据
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
oneRes, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}})
if err != nil{fmt.Println("插入单条记录失败:",err)
return
}else {
fmt.Println(oneRes)
}
// 批量插入
ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
docs := make([]interface{}, 100)
for i := 0; i < 100; i++{
docs[i] = bson.D{{"name", "name"+strconv.Itoa(i)}, {"value", i}}
}
manyRes, err := collection.InsertMany(ctx, docs)
if err != nil {
fmt.Println("批量插入失败:",err)
return
}else {
fmt.Println(manyRes)
}