golang中连接mongo数据库并进行 *** 作

golang中连接mongo数据库并进行 *** 作,第1张

golang中连接mongo数据库并进行 *** 作

golang中连接mongo数据库并进行 *** 作
首先,我们需要下载mongo模块
执行

go get github.com/mongodb/mongo-go-driver/mongo

然后再执行一下
go mod tidy 拉取缺少的模块,移除不用的模块
如果拉的时候timeout,那么去修改一下配置

$env:GOPROXY = "https://goproxy.io"

然后再go mod tidy拉一下。
然后建一个文件夹,用来建立mongo客户端
代码如下

package mgodb

import (
	"context"
	_"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

type mgo struct {
	uri string //数据库网络地址
	database string //要连接的数据库
	collection string //要连接的集合
}

func (m *mgo)Connect() *mongo.Collection {
	ctx , cancel :=context.WithTimeout(context.Background(),10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(m.uri))
	if err != nil {
		log.Print(err)
	}
	collection := client.Database(m.database).Collection(m.collection)
	return collection
}

然后我们还需要在项目启动的时候初始化,连接mongo,在init.go文件里面初始化一下

package models
import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type Database struct {
	Mongo  * mongo.Client
}


var DB *Database


//初始化
func Init() {
	DB = &Database{
		Mongo: SetConnect(),
	}
}
// 连接设置
func SetConnect() *mongo.Client{
	uri := "mongodb+srv://用户名:密码@官方给的.mongodb.net"
	ctx ,cancel := context.WithTimeout(context.Background(),10*time.Second)
	defer cancel()
	client, err :=      mongo.Connect(ctx,options.Client().ApplyURI(uri).SetMaxPoolSize(20))
	if err !=nil{
		fmt.Println(err)
	}
	return client
}

后面,我们就可以去调用mongo提供的api了

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994277.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存