golang连接MongoDB数据库及数据库操作指南
作者:monzaid 时间:2024-01-26 18:14:29
安装配置MongoDB驱动
安装驱动
go get -u github.com/mongodb/mongo-go-driver
初始化模块
go mod init 模块名称
执行go mod tidy
go mod tidy
导入驱动
import (
"context"
"go.mongodb.org/mongo-driver/bson" //BOSN解析包
"go.mongodb.org/mongo-driver/mongo" //MongoDB的Go驱动包
"go.mongodb.org/mongo-driver/mongo/options"
)
获得数据库连接
初始化连接
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var client *mongo.Client
func initDB() (err error) {
// 设置客户端连接配置
clientOptions := options.Client().ApplyURI("mongodb://ip:port")
// 连接到MongoDB
client, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
return err
}
// 检查连接
err = client.Ping(context.TODO(), nil)
if err != nil {
return err
}
return nil
}
func main() {
err := initDB() // 调用输出化数据库的函数
if err != nil {
fmt.Printf("初始化失败!,err:%v\n", err)
return
}else{
fmt.Println("Connected to MongoDB!")
}
}
连接MongoDB的Go驱动程序中有两大类型表示BSON数据:D和Raw。
类型D家族被用来简洁地构建使用本地Go类型的BSON对象。这对于构造传递给MongoDB的命令特别有用。D家族包括四类:
D:一个BSON文档。这种类型应该在顺序重要的情况下使用,比如MongoDB命令。
bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}}
M:一张无序的map。它和D是一样的,只是它不保持顺序。
bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}
A:一个BSON数组。
bson.A{"hello", "world", 3.14159, bson.D{{"abcde", 12345}}}
E:D里面的一个元素。
要使用BSON,需要先导入下面的包:
import "go.mongodb.org/mongo-driver/bson"
Raw类型家族用于验证字节切片。你还可以使用Lookup()从原始类型检索单个元素。如果你不想要将BSON反序列化成另一种类型的开销,那么这是非常有用的。
数据库操作
添加文档
添加单个文档
使用collection.InsertOne()方法插入一条文档记录:
func insertOne(s interface{}) (err error) {
collection := client.Database("datebase").Collection("collection")
insertResult, err := collection.InsertOne(context.TODO(), s)
if err != nil {
return err
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
return nil
}
测试:
s := struct{name string
age int
}{"tom", 20}
err := insertOne(s)
if err != nil{
fmt.Printf("添加文档失败!,err:%v\n", err)
}
添加多个文档
使用collection.InsertMany()方法插入多条文档记录:
func insertMore(s []interface{}) (err error) {
//students := []interface{}{s2, s3}
collection := client.Database("datebase").Collection("collection")
insertManyResult, err := collection.InsertMany(context.TODO(), s)
if err != nil {
return err
}
fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
return nil
}
测试:
type Student struct {
name string
age int
}
s1 := Student{name: "tom", age: 20}
s2 := Student{name: "kite", age: 21}
s3 := Student{name: "rose", age: 22}
ss := []interface{}{s1, s2, s3}
insertMore(ss)
if err != nil{
fmt.Printf("添加多个文档失败!,err:%v\n", err)
}
查找文档
func find() (err error){
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
collection := client.Database("datebase").Collection("collection")
cur, err := collection.Find(ctx, bson.D{})
if err != nil {
return err
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var result bson.D
err := cur.Decode(&result)
if err != nil {
return err
}
fmt.Printf("result: %v\n", result)
}
if err := cur.Err(); err != nil {
return err
}
return nil
}
更新文档
func update() (err error) {
ctx := context.TODO()
defer client.Disconnect(ctx)
c := client.Database("datebase").Collection("collection")
update := bson.D{{"$set", bson.D{{"attr1", "value1"}, {"attr2", "value2"}}}}
ur, err := c.UpdateMany(ctx, bson.D{{"old_attr1", "old_value1"}}, update)
if err != nil {
return err
}
fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
return nil
}
删除文档
func del() (err error) {
c := client.Database("datebase").Collection("collection")
ctx := context.TODO()
dr, err := c.DeleteMany(ctx, bson.D{{"attr1", "value1"}})
if err != nil {
return err
}
fmt.Printf("ur.ModifiedCount: %v\n", dr.DeletedCount)
return nil
}
来源:https://blog.csdn.net/ymxyld/article/details/124931029
标签:golang,mongodb,连接
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python列表生成器常用迭代器示例详解
2023-11-16 01:35:12
Python的Flask框架中使用Flask-Migrate扩展迁移数据库的教程
2024-01-19 06:38:45
python爬虫看看虎牙女主播中谁最“顶”步骤详解
2022-03-31 09:30:33
![](https://img.aspxhome.com/file/2023/2/84152_0s.png)
bootstrap-table+treegrid实现树形表格
2024-04-29 13:12:53
![](https://img.aspxhome.com/file/2023/2/132832_0s.jpg)
JavaScript 题型问答有答案参考
2024-04-19 10:44:41
如何处理包含JavaScript语句时的间隔符?
2009-11-14 20:39:00
详细介绍Python中的set集合
2023-07-26 07:35:03
python字典排序的方法
2021-06-16 03:43:40
![](https://img.aspxhome.com/file/2023/6/75276_0s.png)
golang切片内存应用技巧详解
2024-05-21 10:19:38
Go语言开发框架反射机制及常见函数示例详解
2024-02-16 17:23:19
![](https://img.aspxhome.com/file/2023/5/105135_0s.png)
Python GUI和游戏开发从入门到实践
2021-01-09 15:30:47
python爬虫爬取淘宝商品信息(selenum+phontomjs)
2022-07-07 05:40:52
![](https://img.aspxhome.com/file/2023/9/72869_0s.jpg)
Python中如何导入类示例详解
2023-05-09 08:35:58
零基础写python爬虫之urllib2使用指南
2022-10-17 04:00:44
![](https://img.aspxhome.com/file/2023/4/70214_0s.png)
js控制输入框获得和失去焦点时状态显示的方法
2024-04-17 10:24:04
详解BurpSuite安装和配置
2023-12-30 17:32:12
![](https://img.aspxhome.com/file/2023/0/99390_0s.jpg)
设计中基于人类学的田野调查与比较研究法 ——浅谈用研与竞品分析方法之理论基础
2009-08-31 16:45:00
![](https://img.aspxhome.com/file/UploadPic/20098/31/0908_tianye-investigate_01-61s.jpg)
Python使用pygame模块编写俄罗斯方块游戏的代码实例
2021-11-15 02:29:29
![](https://img.aspxhome.com/file/2023/3/69533_0s.png)
Python控制台输出时刷新当前行内容而不是输出新行的实现
2022-11-28 23:38:22
分享4个Python中高效省时的技巧
2021-02-14 22:32:09
![](https://img.aspxhome.com/file/2023/4/131314_0s.png)