Mongodb环境搭建及Go中的使用

Go语言操作mongodb_go mongodb-CSDN博客文章浏览阅读1.5k次。以上就是今天要讲的内容,如何使用go语言操作mongodb,展示了mongodb的部分指令,而mongodb提供的指令远不止这些,在学习的过程中做笔记,以防日后需要使用mongodb会忘记怎么使用,毕竟好记性不如烂笔头。_go mongodbhttps://blog.csdn.net/m0_56137272/article/details/132629538一文教你Go语言如何轻松使用MongoDB_go mongodb-CSDN博客文章浏览阅读1.1k次。本文档详细介绍了如何使用Go语言对MongoDB进行基础操作。我们将学习如何使用Go连接MongoDB、插入文档、查询文档、更新文档和删除文档。_go mongodbhttps://blog.csdn.net/weixin_59801183/article/details/130574600Go语言中使用MongoDB:完整指南-Golang-PHP中文网MongoDB是一种高性能、开源、文档型的NoSQL数据库,被广泛应用于Web应用、大数据以及云计算领域。而Go语言则是一种快速、开发效率高、代码可维护性强的编程语言。本文将为您完整介绍如何在Go语言中使用MongoDB。一、安装MongoDB在使用MongoDB之前,需要先在您的系统中安装MongoDB。在Linux系统下,可以通过如下命令安装:sudoicon-default.png?t=N7T8https://www.php.cn/faq/561436.htmlMongoDB笔记-阿里云开发者社区MongoDB笔记icon-default.png?t=N7T8https://developer.aliyun.com/article/1470062?spm=a2c6h.14164896.0.0.6cd847c5ul924S&scm=20140722.S_community@@%E6%96%87%E7%AB%A0@@1470062._.ID_1470062-RL_mongodb-LOC_search~UND~community~UND~item-OR_ser-V_3-P0_0

Docker安装MongoDB

1、拉取镜像

docker pull mongo:4.4

2、创建mongo数据持久化目录

mkdir /home/mongodb/data -p

3、运行容器

docker run -itd --name mongo -v /home/mongodb/data:/data/db -p 27017:27017 mongo:4.4 --auth

4、登录mongo容器,并进入到【admin】数据库

docker exec -it mongo mongo admin

注意:最新版的mongo镜像,mongo命令行已经改成了mongosh

image

5、创建一个用户,mongo 默认没有用户

db.createUser({ user:'root',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},'readWriteAnyDatabase']});

【user:‘root’ 】:设置用户名为root

【pwd:‘123456’】:设置密码为123456

【role:‘userAdminAnyDatabase’】:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限

【db: ‘admin’】:可操作的数据库

【‘readWriteAnyDatabase’】:赋予用户读写权限

image

6、连接mongo数据库

db.auth('root', '123456')

image

7、测试数据库,插入一条语句

db.user.insert({"name":"zhangsan","age":18})

image

8、测试数据库,查询刚才插入的语句

db.user.find()

image

使用官方驱动

一、连接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
}

使用mgo库

在Go语言中,使用MongoDB需要安装第三方包mgo。可以通过如下命令安装:

1

go get gopkg.in/mgo.v2

接下来,我们可以编写以下代码来连接MongoDB:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

package main

import (

    "fmt"

    "gopkg.in/mgo.v2"

)

func main() {

    session, err := mgo.Dial("localhost:27017")

    if err != nil {

        panic(err)

    }

    defer session.Close()

    collection := session.DB("test").C("users")

    fmt.Println(collection)

}

这段代码会连接到MongoDB中的test数据库,并返回users集合。其中,session是mgo.Session类型的变量,代表着客户端与MongoDB的连接。而defer关键字会保证在程序结束前执行session.Close(),即关闭连接。最后,我们通过fmt.Println()函数输出collection的值,来验证数据库连接是否成功。

插入和查询文档

在MongoDB中,文档是数据的基本单位,类似于关系型数据库中的行。Go语言可以通过mgo包来对文档进行插入和查询操作。以下代码可以实现向MongoDB中的users集合中插入一条文档:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

package main

import (

    "fmt"

    "gopkg.in/mgo.v2"

    "time"

)

type User struct {

    Name     string `bson:"name"`

    Age      int    `bson:"age"`

    Email    string `bson:"email"`

    CreateAt time.Time `bson:"create_at"`

}

func main() {

    session, err := mgo.Dial("localhost:27017")

    if err != nil {

        panic(err)

    }

    defer session.Close()

    collection := session.DB("test").C("users")

    user := User{

        Name:     "Alice",

        Age:      28,

        Email:    "alice@example.com",

        CreateAt: time.Now(),

    }

    err = collection.Insert(user)

    if err != nil {

        panic(err)

    }

    var result []User

    err = collection.Find(nil).Sort("-create_at").Limit(10).All(&result)

    if err != nil {

        panic(err)

    }

    fmt.Println(result)

}

其中,我们首先定义了一个User结构体,用于描述数据库中的文档。在main函数中,我们首先创建了一个User类型的变量user,并初始化了其字段。然后,我们通过collection.Insert()方法将其插入到users集合中。最后,我们使用collection.Find()方法查询了users集合中所有文档,并按照create_at字段进行倒序排序、限制返回结果数量为10,最终输出查询结果。

更新和删除文档

在MongoDB中,可以通过Update方法来更新文档,通过Remove方法来删除文档。以下代码可以实现在users集合中将名字为Alice的文档的年龄更新为30,然后再将其删除:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

user := User{

    Name:     "Alice",

    Age:      30,

    Email:    "alice@example.com",

    CreateAt: time.Now(),

}

err = collection.Update(bson.M{"name": "Alice"}, user)

if err != nil {

    panic(err)

}

err = collection.Remove(bson.M{"name": "Alice"})

if err != nil {

    panic(err)

}

其中,bson.M是mgo包中的一种类型,用于描述MongoDB中的文档。在Update和Remove方法中,我们可以使用bson.M来指定更新和删除的文档。

SpringBoot整合mongoDB

1、添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
            <version>2.3.9.RELEASE</version>
        </dependency>

2、添加yml配置

spring:
  data:
    mongodb:
      uri: mongodb://root:123456@192.168.233.128:27017/admin

3、测试

package cn.tedu.springboot_quick;
import cn.tedu.springboot_quick.entity.mongo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;
@SpringBootTest
class MongoDBTests {
    
    @Autowired
    public MongoTemplate mongoTemplate;
    /**
     * 保存
     */
    @Test
    public void save() {
        Person person = new Person();
        person.setName("张三");
        person.setAge(18);
        mongoTemplate.save(person);
    }
    /**
     * 多条件查询
     */
    @Test
    public void find() {
        //设置查询条件 age小于30,且person_name="张三"
        Criteria criteria = Criteria.where("age").lt(30)
                .and("person_name").is("张三");
        //设置查询条件
        Query query = new Query(criteria);
        //查询
        List<Person> list = mongoTemplate.find(query, Person.class);
        for (Person person : list) {
            System.out.println(person);
        }
    }
    /**
     * 分页查询
     */
    @Test
    public void findPage() {
        //设置查询条件 age小于30,且person_name="张三"
        Criteria criteria = Criteria.where("age").lt(30)
                .and("person_name").is("张三");
        //根据条件 查询总数
        Query queryCount = new Query(criteria);
        long count = mongoTemplate.count(queryCount, Person.class);
        //查询当前页的数据列表, 查询第二页,每页查询2条
        Query queryLimit = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("age")))
                .limit(2)//每页查询条数
                .skip(0); //从第几页开始 (page-1)*size
        List<Person> list = mongoTemplate.find(queryLimit, Person.class);
        for (Person person : list) {
            System.out.println(person);
        }
    }
    /**
     * 更新数据
     */
    @Test
    public void update() {
        //设置查询条件 person_name="张三",且 age等于18
        Criteria criteria = Criteria.where("person_name").is("张三").and("age").is(18);
        //设置更新条件
        Query query = new Query(criteria);
        //设置更新数据
        Update update = new Update();
        update.set("name", "李四");
        update.set("address","新华联梦想城");
        mongoTemplate.upsert(query, update, Person.class);
    }
    /**
     * 删除数据
     */
    @Test
    public void dlete() {
        mongoTemplate.remove(Query.query(Criteria.where("person_name").is("王五")), Person.class);
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值