Golang 连接 MongoDB使用连接池

可以免费试用 MongoDB ,500MB 平时做测试没有问题啦,连接数据库可能因为网络有点慢,但是我们是测试啊,不在乎这点吧~

 

这是怎么申请试用版的博客,感谢这位大佬。注册好用起来很方便~ 传送门 https://www.cnblogs.com/xybaby/p/9460634.html

 

连接数据库选择的驱动是 mongo-go-driver , 传送门 https://github.com/mongodb/mongo-go-driver/tree/master/examples/documentation_examples

 

具体操作是这样的,在GOPATH,或者项目目录下。

 

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

 

 如果用的是  Go Modules  引入后会爆红!所以我们需要 go mod tidy 。在国内你是知道的,所以我们这样。

 

powershell

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

go mod tidy

 

然后下面是代码

建一个文件夹名字是 mgodb / mgo.go

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)
	defer cancel() //养成良好的习惯,在调用WithTimeout之后defer cancel() 
	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
}

 

基本就是这样连接了,下面我们来测试耗时在哪。 在当前文件夹创建 mgodb / mgo_test.go  Goland会自动识别这是测试文件。代码

 

package mgodb

import (
	"fmt"
	"testing"
)

func TestMgo_Connect(t *testing.T) {
	var mgo = &mgo{
		"mongodb+srv://user:password@官网给你的.mongodb.net",
		"MainSite",
		"UsersM12",
	}
        
         mgo.Connect()
	//collection :=mgo.Connect()
	//fmt.Printf("%T\n",collection)
}

 

可以直接在 Goland 里执行,但是在控制台功能更多。

 

在这里我们需要用到 Graphviz 绘图软件 ,记得在环境变量配置一下。 传送门 : http://www.graphviz.org/ 

 

我们在命令行里执行测试文件

 

 go test -bench . -cpuprofile cpu.out

 

这样会生成可执行文件  mgodb.test.exe 和 cpu.out

 

 go tool pprof cpu.out

 

这时会有一个交互界面在里面输入 web

 

(pprof) web
(pprof) exit

 就可以打开这张图片,svg 不能上传,大概可以看出连接花费了630ms

 

  大概就是这样了,查询的语法都在 github那个传送门里,可以去看一下。

 

 

这是我现在使用的代码可以参考一下。

在 和 mgodb 文件夹下 建一个 initDB.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
}

 

 

mgodb 里的 mgo.db 现在的代码是这样的 使用起来比较简单,删除和插入文档,只需要一个唯一匹配的键值对就可以了

 

 

package mgodb

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

type mgo struct {
	database   string
	collection string
}

func NewMgo(database, collection string) *mgo {

	return &mgo{
		database,
		collection,
	}
}

// 查询单个
func (m *mgo) FindOne(key string, value interface{}) *mongo.SingleResult {
	client := models.DB.Mongo
	collection, _ := client.Database(m.database).Collection(m.collection).Clone()
	//collection.
	filter := bson.D{{key, value}}
	singleResult := collection.FindOne(context.TODO(), filter)
	return singleResult
}

//插入单个
func (m *mgo) InsertOne(value interface{}) *mongo.InsertOneResult {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	insertResult, err := collection.InsertOne(context.TODO(), value)
	if err != nil {
		fmt.Println(err)
	}
	return insertResult
}

//查询集合里有多少数据
func (m *mgo) CollectionCount() (string, int64) {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	name := collection.Name()
	size, _ := collection.EstimatedDocumentCount(context.TODO())
	return name, size
}

//按选项查询集合 Skip 跳过 Limit 读取数量 sort 1 ,-1 . 1 为最初时间读取 , -1 为最新时间读取
func (m *mgo) CollectionDocuments(Skip, Limit int64, sort int) *mongo.Cursor {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	SORT := bson.D{{"_id", sort}} //filter := bson.D{{key,value}}
	filter := bson.D{{}}
	findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
	//findOptions.SetLimit(i)
	temp, _ := collection.Find(context.Background(), filter, findOptions)
	return temp
}

//获取集合创建时间和编号
func (m *mgo) ParsingId(result string) (time.Time, uint64) {
	temp1 := result[:8]
	timestamp, _ := strconv.ParseInt(temp1, 16, 64)
	dateTime := time.Unix(timestamp, 0) //这是截获情报时间 时间格式 2019-04-24 09:23:39 +0800 CST
	temp2 := result[18:]
	count, _ := strconv.ParseUint(temp2, 16, 64) //截获情报的编号
	return dateTime, count
}

//删除文章和查询文章
func (m *mgo) DeleteAndFind(key string, value interface{}) (int64, *mongo.SingleResult) {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	filter := bson.D{{key, value}}
	singleResult := collection.FindOne(context.TODO(), filter)
	DeleteResult, err := collection.DeleteOne(context.TODO(), filter, nil)
	if err != nil {
		fmt.Println("删除时出现错误,你删不掉的~")
	}
	return DeleteResult.DeletedCount, singleResult
}

//删除文章
func (m *mgo) Delete(key string, value interface{}) int64 {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	filter := bson.D{{key, value}}
	count, err := collection.DeleteOne(context.TODO(), filter, nil)
	if err != nil {
		fmt.Println(err)
	}
	return count.DeletedCount

}

//删除多个
func (m *mgo) DeleteMany(key string, value interface{}) int64 {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	filter := bson.D{{key, value}}

	count, err := collection.DeleteMany(context.TODO(), filter)
	if err != nil {
		fmt.Println(err)
	}
	return count.DeletedCount
}

 

 

应该知道怎么初始化吧

 文件结构是这样的,models 在根目录下

 

 

package main



func main() {
	models.Init() //初始化数据库
	app := newApp()
	routers.Router(app)         // 页面访问
	app.Run(iris.Addr(":3000")) // 火箭发射
}

 

转载于:https://www.cnblogs.com/Addoil/p/m12.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 为了连接Mongodb数据库,首先需要安装Mongodb驱动,然后就可以使用下面的代码来连接数据库了: ``` package main import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // 连接字符串 clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") // 连接MongoDB client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } // 检查连接 err = client.Ping(context.TODO(), nil) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!") } ``` 在上面的代码中,我们使用了`mongo-driver`包来连接Mongodb数据库。首先,我们需要创建一个连接字符串,然后使用`mongo.Connect`函数来连接数据库。最后,我们使用`client.Ping`函数来检查连接是否正常。 如果你想了解更多关于如何使用Golang连接Mongodb数据库的信息,可以参考MongoDB官方文档: https://docs.mongodb.com/drivers/go/ ### 回答2: 使用Golang连接MongoDB数据库可以使用第三方库 like "go.mongodb.org/mongo-driver/mongo"。以下是一个简单的示例代码,展示了如何连接MongoDB数据库,并执行一些基本的操作: ```go package main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // 设置MongoDB连接URI uri := "mongodb://localhost:27017" // 设置连接选项 clientOptions := options.Client().ApplyURI(uri) // 连接MongoDB client, err := mongo.Connect(context.Background(), clientOptions) if err != nil { log.Fatal(err) } // 断开与数据库的连接(记得在程序结束前调用) defer func() { if err = client.Disconnect(context.Background()); err != nil { log.Fatal(err) } }() // 检查是否成功连接到数据库 err = client.Ping(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Println("Successfully connected to MongoDB!") // 在指定的数据库和集合中查找文档 collection := client.Database("test").Collection("users") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // 查询条件 filter := bson.M{"name": "John Doe"} // 执行查询 cur, err := collection.Find(ctx, filter) if err != nil { log.Fatal(err) } defer cur.Close(ctx) // 遍历结果 for cur.Next(ctx) { var user bson.M err := cur.Decode(&user) if err != nil { log.Fatal(err) } fmt.Println(user) } if err := cur.Err(); err != nil { log.Fatal(err) } } ``` 上述示例演示了连接MongoDB数据库、执行查询等常见操作,您可以根据自己的需求进行修改和扩展。这个示例代码适用于Golang 1.12及更高版本。为了正确运行代码,您需要将代码中的MongoDB连接URI,数据库名称,集合名称和查询条件更改为您实际使用的值。 ### 回答3: 要在Golang连接Mongodb数据库,首先需要安装相应的驱动程序。Go官方提供了一个Mongodb驱动程序包,我们可以使用它来实现连接。 首先,使用go get命令来安装该驱动程序: ```shell go get go.mongodb.org/mongo-driver/mongo ``` 然后,在你的Golang代码中导入该驱动程序包: ```go import ( "context" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) ``` 接下来,我们需要创建一个MongoDB客户端连接。可以使用mongo.Connect函数来创建一个客户端连接。以下是一个示例代码: ```go // 创建一个用于管理MongoDB的客户端 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) // 检查连接错误 if err != nil { log.Fatal(err) } ``` 在上述代码中,我们创建了一个mongo.Client类型的client变量,该变量将用于执行数据库操作。使用options.Client().ApplyURI函数来指定MongoDB连接字符串。上面的示例使用本地主机和默认端口号来连接MongoDB。 然后,我们可以通过调用client.Connect方法来建立连接: ```go err = client.Connect(context.TODO()) // 检查连接错误 if err != nil { log.Fatal(err) } ``` 现在,我们已经成功建立了与MongoDB数据库的连接。我们可以使用这个client对象来执行各种数据库操作,如插入、更新、查询等。 需要注意的是,在处理完毕后,我们应该关闭与MongoDB数据库的连接。可以使用client.Disconnect方法来关闭连接: ```go err = client.Disconnect(context.TODO()) // 检查连接错误 if err != nil { log.Fatal(err) } ``` 总结:在Golang连接MongoDB数据库需要先安装驱动程序包,然后导入驱动程序包,创建一个MongoDB客户端连接,最后关闭连接。通过这个客户端连接可以执行各种数据库操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值