Go 操作 mongoDB

Author mogd 2022-05-06
Update mogd 2022-05-25
Adage Take 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包文档

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-256SCRAM-SHA-1MONGODB-CRPLAIN、GSSAPIMONGODB-X509MONGODB-AWS

AuthMechanismProperties: 用于为某些机制指定其他配置选项

  • SERVICE_NAME: 用于 GSSAPI 身份验证的服务名称。默认为 mongodb
  • CANONICALIZE_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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值