Author mogd 2022-05-06
Update mogd 2022-05-25
AdageTake action and dive in head first.
注:写的不是很好,后面集合和文档的操作没细写,只是贴了代码
代码
目录
Go 操作 mongoDB
一、连接数据库
安装
go get go.mongodb.org/mongo-driver/mongo
1.1 代码解析
连接数据库,这里封装成一个函数,返回 mongo.Client
// MongoClient Create a database connection
//
// return *mongo.Client
func MongoClient() *mongo.Client {
credential := options.Credential{
AuthMechanism: "SCRAM-SHA-1",
Username: "mogd",
Password: "admin",
}
// ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
// defer cancel()
clientOpts := options.Client().ApplyURI(uri).SetAuth(credential)
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
panic(err)
}
return client
}
mongo.Connect()必须传递一个 context 和一个 options.ClientOptions 对象,client options 用于设置连接字符串,以及配置 driver 的设置,如 write concern, socket timeout 等等;mongo.Connect() 会返回一个 *mongo.Client 和一个 error,通过 *mongo.Client 来操作 mongodb
options.ClientOptions 的调用顺序会导致连接信息的不同,例如在 SetAuth 之前调用 ApplyURI,则 SetAuth 的凭据覆盖连接字符串中的值,反之 ApplyURI 的值会覆盖 SetAuth
这里的代码中 SetAuth 传入了 options.Credential 结构体,用于传递 mongodb 的身份验证凭据,看一下 options.Credential 的定义
type Credential struct {
AuthMechanism string
AuthMechanismProperties map[string]string
AuthSource string
Username string
Password string
PasswordSet bool
}
AuthMechanism: 用于身份验证的机制,SCRAM-SHA-256、SCRAM-SHA-1、MONGODB-CR、PLAIN、GSSAPI、MONGODB-X509 和 MONGODB-AWS
AuthMechanismProperties: 用于为某些机制指定其他配置选项
SERVICE_NAME: 用于GSSAPI身份验证的服务名称。默认为mongodbCANONICALIZE_HOST_NAME:true or false,驱动程序将规范化主机名以进行GSSAPI身份验证SERVICE_REALM:GSSAPI认证的服务领域SERVICE_HOST: 用于GSSAPI身份验证的主机名AWS_SESSION_TOKEN: 用于MONGODB-AWS身份验证的 AWS 令牌
AuthSource: 用于身份验证的数据库名称
username: 用户名
Password: 密码
PasswordSet: 对于 GSSAPI,如果指定了密码,则必须为 true,即使密码为空字符串,如果未指定密码,则为 false,表示应从正在运行的进程的上下文中获取密码。对于其他机制,该字段被忽略
数据库关闭
通过 mongo.Connect() 获取到数据库连接后,当应用程序不再使用连接,需要关闭连接,否则会一直占用数据库的连接数;使用 client.Disconnect() 关闭
defer func() {
if err := Client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
这里使用 defer 关键字,即在函数退出前,执行数据库连接的关闭操作
1.2 官方直连完整示例
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func main() {
// Create a Client to a MongoDB server and use Ping to verify that the
// server is running.
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
log.Fatal

本文档详细介绍了如何使用Go语言操作MongoDB,包括连接数据库、管理数据库、操作集合和文档,以及处理常见错误。重点讲解了连接数据库的代码解析、官方连接示例,以及数据库操作如ListDatabases和DropDatabase。同时,还涵盖了集合的ListCollection、DropCollection和CreateCollection方法。在错误记录部分,讨论了连接Replica Set时可能出现的问题及解决方案。
最低0.47元/天 解锁文章
728





