Go语言操作mongodb

目录

一、连接mongodb

1.目录结构

2.安装mongodb驱动

3.连接mongodb

二、定义模型

三、添加文档

1.单个添加

 2.批量添加

四、删除文档

1.删除单个

五、更新文档

1.更新单条

2.更新多条

六、查询

1.条件查询

 2.投影查询

3.limit

4.offset

5. order by desc

6.模糊查询

 7.比较查询

8. 包含查询

9. and查询

总结


前言:本文主要演示了如何使用go语言操作mongodb,包括连接mongodb,操作数据等等。


一、连接mongodb

1.目录结构

2.安装mongodb驱动

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

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

3.连接mongodb

package mongodb

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

var client *mongo.Client
var coll *mongo.Collection

func Init() (err error) {
	// 1.连接mongodb
	client, err = mongo.Connect(context.Background(),
		options.Client().ApplyURI("mongodb://localhost:27017").
			SetConnectTimeout(5*time.Second))
	if err != nil {
		fmt.Println(err)
		return err
	}

	if err = client.Ping(context.Background(), nil); err != nil {
		fmt.Println(err)
		return err
	}
    
    // 由于都是对同一个集合进行操作,所以在初始化mongodb时就选择了集合,防止后续出现大量重复代码
	coll = client.Database("db").Collection("stu")
	return
}

func GetClient() *mongo.Client {
	return client
}

func Close() {
	_ = client.Disconnect(context.Background())
}

二、定义模型

package models

type Student struct {
	ID   int    `bson:"_id"`
	Age  int    `bson:"age"`
	Name string `bson:"name"`
	Addr string `bson:"address"`
}

三、添加文档

1.单个添加

package mongodb

import (
	"context"
	"fmt"
	"mongo/models"
)

func InsertStudent(p *models.Student) error {
	// 插入文档
	if _, err := coll.InsertOne(context.Background(), p); err != nil {
		return err
	}
	fmt.Println("Document inserted successfully!")
	return nil
}

 2.批量添加

package mongodb

import (
	"context"
	"fmt"
	"mongo/models"
)


func InsertStudents(p []interface{}) error {

	// 插入多条文档
	if _, err := coll.InsertMany(context.Background(), p); err != nil {
		return err
	}
	fmt.Println("Document inserted successfully!")
	return nil
}
package main

import (
	"fmt"
	"mongo/models"
	"mongo/mongodb"
)

func main() {
	// 1.连接mongodb
	if err := mongodb.Init(); err != nil {
		return
	}
	defer mongodb.Close()

	stus := []interface{}{
		models.Student{
			ID:   1,
			Age:  18,
			Name: "alice",
			Addr: "beijing",
		},
		models.Student{
			ID:   2,
			Age:  19,
			Name: "bob",
			Addr: "shanghai",
		},
		models.Student{
			ID:   3,
			Age:  20,
			Name: "charlie",
			Addr: "guangzhou",
		},
	}
	if err := mongodb.InsertStudents(stus); err != nil {
		return
	}
}

四、删除文档

1.删除单个

package mongodb

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
)

func DeleteStudent(p int) error {

	// 过滤条件
	fil := bson.M{"_id": p}

	// 删除文档
	if _, err := coll.DeleteOne(context.Background(), fil); err != nil {
		return err
	}
	fmt.Println("Document Delete successfully!")
	return nil
}

五、更新文档

1.更新单条

package mongodb

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

// UpdateStudent 根据传入的参数进行更新
func UpdateStudent(p *models.Student) error {

	// 根据条件筛选要更新的文档
	filter := bson.M{"_id": p.ID}
	update := bson.M{"$set": p}

	// 更新文档
	if _, err := coll.UpdateOne(context.Background(), filter, update); err != nil {
		return err
	}
	fmt.Println("Document Update successfully!")
	return nil
}

2.更新多条

// UpdateStudents 修改所有符合条件的数据update stu set age = 99 where name = ?
func UpdateStudents(p string) error {

	// 根据条件筛选要更新的文档
	filter := bson.M{"name": p}
	update := bson.M{"$set": bson.M{"age": 99}}

	// 更新文档
	if _, err := coll.UpdateMany(context.Background(), filter, update); err != nil {
		return err
	}
	fmt.Println("Document Update successfully!")
	return nil
}

六、查询

1.条件查询

package mongodb

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

// QueryStudentByID select * from stu where id = ?
func QueryStudentByID(p int) error {
	filter := bson.M{"_id": p} // 根据条件筛选要更新的文档

	var s models.Student
	// 插入文档
	err := coll.FindOne(context.Background(), filter).Decode(&s)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	fmt.Printf("Document Find: %+v", s)

	return nil
}

 2.投影查询

// QueryStudentByID1 投影查询,类似select name age from stu where id = ?
func QueryStudentByID1(p int) error {
	filter := bson.M{"_id": p} // 根据条件筛选要更新的文档

	// 投影选项
	d := bson.D{
		{"name", 1},
		{"age", 1},
	}
	
	// 查询文档
	res, err := coll.Find(context.Background(), filter, options.Find().SetProjection(d))
	if err != nil {
		return err
	}
	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}
	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}

	return nil
}

3.limit

// QueryStudent 分页查询 select * from stu limit ?
func QueryStudent(size int64) error {

	// 分页选项
	l := options.Find().SetLimit(size)
	filter := bson.M{}
	// 插入文档
	res, err := coll.Find(context.TODO(), filter, l)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}
	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}

	return nil
}

4.offset

// QueryStudentByID3 跳过指定数量的数据
func QueryStudentByID3(p int64) error {
	// 跳跃选项
	l := options.Find().SetSkip(p)
	filter := bson.M{}

	// 插入文档
	res, err := coll.Find(context.TODO(), filter, l)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}

	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}

	return nil
}

5. order by desc

// QueryStudent2 对查询结果进行降序排序,入参为1升序,入参-1降序
func QueryStudent2(p int) error {
    // select * from stu order by age desc
	// 排序选项
	s := options.Find().SetSort(bson.D{{"age", p}})
	filter := bson.M{}

	// 3.插入文档
	res, err := coll.Find(context.TODO(), filter, s)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}
	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}

	return nil
}

6.模糊查询

// QueryStudent3 模糊查询 select * from stu where name like %?%
func QueryStudent3(p string) error {
	filter := bson.M{
		"name": bson.M{
			"$regex": p,
		},
	}

	//filter1 := bson.M{
	//	"name": bson.M{
	//		"$regex": fmt.Sprintf("^%s", p),    //name like ?%
	//	},
	//}

	// 查询
	res, err := coll.Find(context.TODO(), filter)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}

	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}
	return nil
}

 7.比较查询

// QueryStudent4 比较查询 select * from stu where age > ?
func QueryStudent4(p int) error {
	// 过滤条件
	filter := bson.M{
		"age": bson.M{
			"$gt": p, // age > p
			// $lt <
			// $gte >=
			// $lte <=
			// $ne !=
		},
	}

	// 查询
	res, err := coll.Find(context.TODO(), filter)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}

	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}
	return nil
}

8. 包含查询


// QueryStudent5 包含查询 select * from stu where age in [s, e]
func QueryStudent5(s, e int) error {
	// 过滤条件
	filter := bson.M{
		"age": bson.M{
			"$in": []int{s, e}, // age in [s, e]
			// "$nin": []int{s, e}, // age not in [s, e]
		},
	}

	// 查询
	res, err := coll.Find(context.TODO(), filter)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}

	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}
	return nil
}

9. and查询

// QueryStudent6 连接查询 select * from stu where age = ? and name = ?
func QueryStudent6(age int, name string) error {
	// 过滤条件
	filter := bson.M{

		// age = ? and name = ?
		"$and": []bson.M{
			{"age": age},
			{"name": name},
		},

		// age > ? and name = ?
		//"$and": []bson.M{
		//	bson.M{"age": bson.M{"$gt": 20}},
		//	bson.M{"name": "zhaoliu"},
		//},

		// age > ? or name = ?
		//"$or": []bson.M{
		//	bson.M{"age": bson.M{"$gt": 20}},
		//	bson.M{"name": "zhaoliu"},
		//},
	}

	// 查询
	res, err := coll.Find(context.TODO(), filter)
	if err != nil {
		return err
	}

	fmt.Println("Document Find successfully!")
	defer res.Close(context.Background())

	var stus []models.Student
	if err = res.All(context.Background(), &stus); err != nil {
		return err
	}

	for _, s := range stus {
		fmt.Printf("Document found: %+v\n", s)
	}
	return nil
}


总结

以上就是今天要讲的内容,如何使用go语言操作mongodb,展示了mongodb的部分指令,而mongodb提供的指令远不止这些,在学习的过程中做笔记,以防日后需要使用mongodb会忘记怎么使用,毕竟好记性不如烂笔头。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在使用 Go 语言操作 MongoDB 数据库时,可以使用事务来管理写入、删除等操作。 首先,在开启事务之前,需要先获取一个 MongoDB 连接: ``` client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { // handle error } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() err = client.Connect(ctx) if err != nil { // handle error } ``` 然后,可以使用 `client.Database()` 方法来获取数据库的句柄,再使用 `Database.StartSession()` 方法来开启一个事务: ``` sess, err := client.Database("mydb").StartSession() if err != nil { // handle error } defer sess.EndSession(ctx) ``` 在事务中执行写入、删除等操作时,需要使用 `Session.WithTransaction()` 方法来包裹这些操作,并使用 `Session.AbortTransaction()` 方法来回滚事务: ``` err = sess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) error { // perform write operations _, err = client.Database("mydb").Collection("mycoll").InsertOne(sessCtx, bson.M{"x": 1}) if err != nil { sess.AbortTransaction(sessCtx) return err } return nil }) if err != nil { // handle error } ``` 在事务中执行的所有操作都会在事务提交之前保存到内存中,并在事务提交时一起写入到数据库中。如果在事务中出现了错误,可以使用 `Session.AbortTransaction()` 方法来回滚事务,所有在事务中执行的操作都不会写入到数据库中。 在事务结 ### 回答2: 在Go语言操作MongoDB,可以使用事务回滚来进行写入、删除等操作。以下是一些基本操作的示例: 1. 初始化MongoDB客户端和数据库连接: ```go clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } database := client.Database("mydatabase") ``` 2. 开启事务: ```go session, err := client.StartSession() if err != nil { log.Fatal(err) } defer session.EndSession(context.TODO()) ``` 3. 事务开始后,可以执行多个操作。例如,插入一条数据: ```go session.StartTransaction() collection := database.Collection("mycollection") doc := bson.D{{"key", "value"}} _, err = collection.InsertOne(session.Context(), doc) if err != nil { session.AbortTransaction(session.Context()) log.Fatal(err) } ``` 4. 执行其他操作,比如删除一条数据: ```go collection := database.Collection("mycollection") filter := bson.D{{"key", "value"}} _, err = collection.DeleteOne(session.Context(), filter) if err != nil { session.AbortTransaction(session.Context()) log.Fatal(err) } ``` 5. 若所有操作都成功执行,提交事务: ```go err = session.CommitTransaction(session.Context()) if err != nil { log.Fatal(err) } ``` 6. 若操作发生错误或者需要回滚,可以调用AbortTransaction()进行事务回滚: ```go session.AbortTransaction(session.Context()) ``` 以上是一个简单的示例,用于展示如何在Go语言中使用事务回滚进行写入和删除操作。实际应用中,可能需要更多的代码和逻辑来处理错误以及处理更复杂的事务操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值