MongoDB 官方支持的 Go 语言驱动,适用于 Go 1.18+ 和 MongoDB 3.6+,提供连接、查询、插入等数据库操作功能,支持多种网络压缩算法。【此简介由AI生成】

MongoDB Go 驱动
MongoDB 官方支持的 Go 语言驱动程序。
[!注意]
Go 驱动 1.17.0 是 1.x 系列的最后一个计划版本。 该版本仅接收关键错误修复,未来新功能和开发 将集中在 2.x 版本驱动中。
环境要求
- Go 1.18 或更高版本。我们将持续支持 Go 的最新版本。
- 运行驱动测试套件需要 Go 1.22 或更高版本。
- MongoDB 3.6 及更高版本。
安装指南
推荐使用 Go modules 方式安装 MongoDB Go 驱动到您的项目中。您可以通过以下两种方式实现:
- 在代码中直接导入
go.mongodb.org/mongo-driver包,构建时自动安装依赖; - 显式执行以下命令进行安装:
go get go.mongodb.org/mongo-driver/mongo
在不支持模块的 Go 版本中使用时,可以通过运行以下 dep 命令来安装驱动程序:
dep ensure -add "go.mongodb.org/mongo-driver/mongo"
使用指南
要开始使用该驱动,请先导入 mongo 包,并通过 Connect 函数创建一个 mongo.Client 实例:
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
在实例化客户端后,务必延迟调用 Disconnect 方法:
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
如需进行更高级的配置和身份验证,请参阅 mongo.Connect 的文档。
调用 Connect 方法不会阻塞服务器发现过程。若需确认是否已找到并连接至 MongoDB 服务器,
可使用 Ping 方法:
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = client.Ping(ctx, readpref.Primary())
要将文档插入到集合中,首先需要从 Client 获取 Database 和 Collection 实例:
collection := client.Database("testing").Collection("numbers")
随后,可使用该 Collection 实例插入文档:
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := collection.InsertOne(ctx, bson.D{{"name", "pi"}, {"value", 3.14159}})
id := res.InsertedID
要使用 bson.D,你需要在导入中添加 "go.mongodb.org/mongo-driver/bson"。
此时,你的导入语句应如下所示:
import (
"context"
"log"
"time"
"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"
)
多种查询方法会返回一个游标(cursor),其使用方式如下:
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cur, err := collection.Find(ctx, bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(ctx)
for cur.Next(ctx) {
var result bson.D
err := cur.Decode(&result)
if err != nil { log.Fatal(err) }
// do something with result....
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
对于返回单个条目的方法,会返回一个 SingleResult 实例:
var result struct {
Value float64
}
filter := bson.D{{"name", "pi"}}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = collection.FindOne(ctx, filter).Decode(&result)
if err == mongo.ErrNoDocuments {
// Do something when no record was found
fmt.Println("record does not exist")
} else if err != nil {
log.Fatal(err)
}
// Do something with result...
更多示例和文档可在 examples 目录及 MongoDB 官方文档网站 查阅。
网络压缩
网络压缩功能可降低 MongoDB 与应用程序之间的带宽需求。
Go 驱动程序支持以下压缩算法:
- Snappy (
snappy):适用于 MongoDB 3.4 及以上版本 - Zlib (
zlib):适用于 MongoDB 3.6 及以上版本 - Zstandard (
zstd):适用于 MongoDB 4.2 及以上版本
指定压缩算法
可通过连接字符串中的 compressors 参数或调用 ClientOptions.SetCompressors 方法启用压缩功能:
opts := options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd")
client, _ := mongo.Connect(context.TODO(), opts)
opts := options.Client().SetCompressors([]string{"snappy", "zlib", "zstd"})
client, _ := mongo.Connect(context.TODO(), opts)
若设置了压缩器,Go 驱动会与服务器协商选择首个双方共有的压缩器。关于服务器配置及默认值,请参阅 networkMessageCompressors。
仅当通信双方均启用网络压缩时,消息才会被压缩;否则消息将以未压缩形式传输。
反馈
如需获取驱动相关帮助,请在 MongoDB 社区论坛 发帖咨询。
新功能建议与缺陷报告请提交至 Jira:https://jira.mongodb.org/browse/GODRIVER
贡献指南
请访问 项目看板 查看待完成任务。详细贡献规范请参阅 贡献指南。
持续集成
提交到 master 分支的代码会自动在 Evergreen 平台执行集成测试。
常见问题
排查高频问题请参考 常见问题文档。
致谢
- Go 地鼠艺术设计 @ashleymcnamara
- 原始 Go 地鼠形象由 Renee French 创作
许可协议
MongoDB Go 驱动遵循 Apache 许可协议 开源。