Go语言学习笔记之golang操作MongoDB数据库

 更新时间:2023年05月25日 11:48:41   作者:PPPsych  
MongoDB是Nosql中常用的一种数据库,这篇文章主要给大家介绍了关于Go语言学习笔记之golang操作MongoDB数据库的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

一 下载安装驱动

官方文档

https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo

下载地址

https://www.mongodb.com/try/download/community

打开客户端

mongo.exe

创建数据库

use golang_db;

创建集合

db.createCollection("student");

下载驱动

go get go.mongodb.org/mongo-driver/mongo

二 go连接到MongoDB

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	var err error
	c, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("MongoDB 连接成功")
	client = c
}

func main() {
	initDB()
}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功

[Done] exited with code=0 in 2.819 seconds

三 BSON简介

MongoDB中的JSON文档存储在名为BSON(二进制编码的JSON)的二进制表中。与其他将JSON数据存储为简单字符串和数字的数据库不同,BSON编码扩展了JSON表示,使其包含额外的类型,如int、long、date、浮点数和decimal128。这使得应用程序更容易可靠地处理、排序和比较数据。

连接MongoDB地Go驱动程序中有两大类型表示BSON数据:DRaw

类型D家族被用来简洁地构建使用本地Go类型地BSON对象。这对于构造传递给MongoDB地命令特别有用。D家族包括四大类:

  • D:一个BSON文档。这种类型应该在顺序重要的情况下使用,比如MongoDB命令。
  • M:一张无序的map。它和D是一样的,只是它不保持顺序。
  • A:一个BSON数组。
  • E:D里面的一个元素。

要使用BSON,需要先导入下面的包:

go.mongodb.org/mongo-driver/bson

下面是一个使用D类型构建地过滤器文档的例子,它可以用来查找name字段与‘张三’或‘李四’匹配的文档:

bson.D{{
	"name",
	bson.D{{
		"$in",
		bson.A{"张三","李四"},
	}},
}}

Raw类型家族用于验证字节切片。还可以使用Lookup()从原始类型检索单个元素。如果不想将BSON反序列化成另一种类型的开销,那么这是非常有用的。

本文只使用D类型。

四 添加文档

4.1 创建一个结构体

type Student struct {
	Name string
	Age  int
}

4.2 添加单个文档

方法:

func (coll *Collection) InsertOne(ctx context.Context, document interface{},
	opts ...*options.InsertOneOptions) (*InsertOneResult, error)

实例演示:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	var err error
	c, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("MongoDB 连接成功")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertOne(s Student) {
	initDB()

	collection := client.Database("golang_db").Collection("student")
	insertResult, err := collection.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("添加了一条文档记录: %v\n", insertResult.InsertedID)
}

func main() {
	s := Student{Name: "Psych", Age: 18}
	insertOne(s)
}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
添加了一条文档记录: ObjectID("62ee3202c3c3f019d63c34ff")

[Done] exited with code=0 in 3.518 seconds

MongoDB中查看:

4.3 添加多个文档

方法:

func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},
	opts ...*options.InsertManyOptions) (*InsertManyResult, error) 

实例演示:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	var err error
	c, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("MongoDB 连接成功")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertMore(students []interface{}) {
	initDB()

	collection := client.Database("golang_db").Collection("student")
	insertManyResult, err := collection.InsertMany(context.TODO(), students)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("添加了多条文档记录: %v\n", insertManyResult.InsertedIDs)
}

func main() {
	s1 := Student{Name: "Klee", Age: 8}
	s2 := Student{Name: "Morax", Age: 1000}
	s3 := Student{Name: "Baal", Age: 500}
	student := []interface{}{s1, s2, s3}
	insertMore(student)
}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
添加了多条文档记录: [ObjectID("62ee337502174a1366f86db2") ObjectID("62ee337502174a1366f86db3") ObjectID("62ee337502174a1366f86db4")]

[Done] exited with code=0 in 2.558 seconds

MongoDB中查看:

五 查找文档

方法:

func (coll *Collection) Find(ctx context.Context, filter interface{},
	opts ...*options.FindOptions) (cur *Cursor, err error)

实例演示:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	var err error
	c, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("MongoDB 连接成功")
	client = c
}

func findData() {
	initDB()

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	collection := client.Database("golang_db").Collection("student")

	// c, err := collection.Find(ctx, bson.D{{Key: "name", Value: "Psych"}})
	// 单个数据查询
	// c, err := collection.Find(ctx, bson.D{{Key: "name", Value: "Morax"}})
	c, err := collection.Find(ctx, bson.D{})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close(ctx)

	for c.Next(ctx) {
		var result bson.D
		err := c.Decode(&result)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("查找结果为: %v\n", result)
		fmt.Printf("result.Map(): %v\n", result.Map()["name"])
	}
	if err := c.Err(); err != nil {
		log.Fatal(err)
	}

}

func main() {
	findData()
}

注释内容为单个数据查询,可自行测试

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
查找结果为: [{_id ObjectID("62ee3202c3c3f019d63c34ff")} {name Psych} {age 18}]
result.Map(): Psych
查找结果为: [{_id ObjectID("62ee337502174a1366f86db2")} {name Klee} {age 8}]
result.Map(): Klee
查找结果为: [{_id ObjectID("62ee337502174a1366f86db3")} {name Morax} {age 1000}]
result.Map(): Morax
查找结果为: [{_id ObjectID("62ee337502174a1366f86db4")} {name Baal} {age 500}]
result.Map(): Baal

[Done] exited with code=0 in 2.482 seconds

六 更新文档

方法:

func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*UpdateResult, error) 
func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*UpdateResult, error)

实例演示:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	var err error
	c, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("MongoDB 连接成功")
	client = c
}

func updateData() {
	initDB()

	ctx := context.TODO()
	defer client.Disconnect(ctx)

	c := client.Database("golang_db").Collection("student")

	update := bson.D{{"$set", bson.D{{Key: "name", Value: "钟离"}, {Key: "age", Value: 1200}}}}
	// 更新条件 name Morax
	// 更新为 name 钟离 age 1200
	ur, err := c.UpdateMany(ctx, bson.D{{Key: "name", Value: "Morax"}}, update)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("修改文档数量: %v\n", ur.ModifiedCount)
}

func main() {
	updateData()
}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
修改文档数量: 1

[Done] exited with code=0 in 2.529 seconds

MongoDB中查看:

七 删除文档

方法:

func (coll *Collection) DeleteMany(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*DeleteResult, error)
func (coll *Collection) DeleteOne(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*DeleteResult, error)

实例演示:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	var err error
	c, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("MongoDB 连接成功")
	client = c
}

func deleteData() {
	initDB()

	ctx := context.TODO()
	defer client.Disconnect(ctx)

	c := client.Database("golang_db").Collection("student")
	dr, err := c.DeleteMany(ctx, bson.D{{Key: "name", Value: "Psych"}})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("删除文档数量: %v\n", dr.DeletedCount)
}

func main() {
	deleteData()
}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
删除文档数量: 1

[Done] exited with code=0 in 3.698 seconds

MongoDB中查看:

总结

到此这篇关于Go语言学习笔记之golang操作MongoDB数据库的文章就介绍到这了,更多相关golang操作MongoDB数据库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Golang学习之无类型常量详解

    Golang学习之无类型常量详解

    对于无类型常量,可能大家是第一次听说,但我们每天都在用,每天都有无数潜在的坑被埋下。本文就来和大家聊聊它的相关注意事项吧,希望对大家有所帮助
    2023-03-03
  • golang框架中跨服务的最佳通信协议和工具

    golang框架中跨服务的最佳通信协议和工具

    在 go 框架中实现跨服务通信的最佳实践包括使用 grpc(适用于低延迟高吞吐量)、http 客户端(适用于 restful api)和消息队列(适用于异步解耦通信),在选择通信方式时,应考虑服务交互模式、性能要求和部署环境等因素
    2024-06-06
  • 使用Golang生成压缩文件的详细教程

    使用Golang生成压缩文件的详细教程

    与其他语言一样,内置标准库默认支持文件压缩功能,本文介绍Golang如何创建压缩文件,增加一个或多个文件生成压缩文件,也可以在压缩文件中创建文件夹,用于对文件进行分类管理,Golang标准库 archive/zip提供了创建和读取压缩文件功能,需要的朋友可以参考下
    2024-01-01
  • Golang实现拓扑排序(DFS算法版)

    Golang实现拓扑排序(DFS算法版)

    这篇文章主要介绍了Golang实现拓扑排序(DFS算法版),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • Go语言实现关闭http请求的方式总结

    Go语言实现关闭http请求的方式总结

    面试的时候问到如何关闭http请求,一般人脱口而出的是关闭response.body,这是错误的。本文为大家整理了三个正确关闭http请求的方法,希望对大家有所帮助
    2023-02-02
  • GoFrame ORM原生方法操作示例

    GoFrame ORM原生方法操作示例

    这篇文章主要为大家介绍了GoFrame ORM原生方法操作示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • Go1.20最新资讯go arena手动管理内存鸽了

    Go1.20最新资讯go arena手动管理内存鸽了

    由于过于繁杂,Go 核心团队成员@Ian Lance Taylor,也表态:目前尚未做出任何决定,也不可能在短期内做出任何决定,可以认为这个提案基本鸽了,今天这篇文章就是给大家同步目前的情况
    2023-11-11
  • 在Golang中使用iota案例详解

    在Golang中使用iota案例详解

    在Go语言中,iota是一个预定义的标识符,用于在常量声明中生成连续的递增值,iota的值从0开始,每次在常量声明中使用时递增,本就给大家讲解一下Golang中iota的使用案例,感兴趣的同学跟着小编一起来看看吧
    2023-07-07
  • Windows10系统下安装Go环境详细步骤

    Windows10系统下安装Go环境详细步骤

    Go语言是谷歌推出的一款全新的编程语言,可以在不损失应用程序性能的情况下极大的降低代码的复杂性,这篇文章主要给大家介绍了关于Windows10系统下安装Go环境的详细步骤,需要的朋友可以参考下
    2023-11-11
  • 详解Golang中gomock的使用场景和方法

    详解Golang中gomock的使用场景和方法

    gomock是Go编程语言的模拟框架, 它与Go的内置测试包很好地集成在一起,但也可以在其他上下文中使用,本文主要介绍了gomock的使用场景和方法,感兴趣的可以了解下
    2024-10-10

最新评论