栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/905323.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号