脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - 使用GO操作MongoDB的方法

使用GO操作MongoDB的方法

2022-10-07 15:18hubb Golang

这篇文章主要介绍了使用GO操作MongoDB,包括安装MongoDB驱动程序连接mongodb的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

安装MongoDB驱动程序

?
1
2
3
4
mkdr mongodb
cd mongodb
go mod init 
go get go.mongodb.org/mongo-driver/mongo

连接MongoDB

创建一个main.go文件
将以下包导入main.go文件中

?
1
2
3
4
5
6
7
8
9
10
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"
   "time"
)

连接MongoDB的URI格式为

?
1
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

单机版

?
1
mongodb://localhost:27017

副本集

?
1
mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017 /?replicaSet = myRepl

分片集群

?
1
mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017

mongo.Connect()接受Context和options.ClientOptions对象,该对象用于设置连接字符串和其他驱动程序设置。
通过context.TODO()表示不确定现在使用哪种上下文,但是会在将来添加一个使用Ping方法来检测是否已正常连接MongoDB

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func main() {
    clientOptions := options.Client().ApplyURI("mongodb://admin:password@localhost:27017")
    var ctx = context.TODO()
    // Connect to MongoDB
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }
    // Check the connection
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
    defer client.Disconnect(ctx)

列出所有数据库

?
1
2
3
4
5
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
   log.Fatal(err)
}
fmt.Println(databases)

在GO中使用BSON对象
MongoDB中的JSON文档以称为BSON(二进制编码的JSON)的二进制表示形式存储。与其他将JSON数据存储为简单字符串和数字的数据库不同,BSON编码扩展了JSON表示形式,例如int,long,date,float point和decimal128。这使应用程序更容易可靠地处理,排序和比较数据。Go Driver有两种系列用于表示BSON数据:D系列类型和Raw系列类型。
D系列包括四种类型:

D:BSON文档。此类型应用在顺序很重要的场景下,例如MongoDB命令。
M:无序map。除不保留顺序外,与D相同。
A:一个BSON数组。
E:D中的单个元素。
插入数据到MongoDB
插入单条文档

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//定义插入数据的结构体
type sunshareboy struct {
    Name string
    Age  int
    City string
}
//连接到test库的sunshare集合,集合不存在会自动创建
collection := client.Database("test").Collection("sunshare")
wanger:=sunshareboy{"wanger",24,"北京"}
insertOne,err :=collection.InsertOne(ctx,wanger)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted a Single Document: ", insertOne.InsertedID)

执行结果如下

使用GO操作MongoDB的方法

同时插入多条文档

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
collection := client.Database("test").Collection("sunshare")
dongdong:=sunshareboy{"张冬冬",29,"成都"}
huazai:=sunshareboy{"华仔",28,"深圳"}
suxin:=sunshareboy{"素心",24,"甘肃"}
god:=sunshareboy{"刘大仙",24,"杭州"}
qiaoke:=sunshareboy{"乔克",29,"重庆"}
jiang:=sunshareboy{"姜总",24,"上海"}
//插入多条数据要用到切片
boys:=[]interface{}{dongdong,huazai,suxin,god,qiaoke,jiang}
insertMany,err:= collection.InsertMany(ctx,boys)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertMany.InsertedIDs)

从MongDB中查询数据

查询单个文档

查询单个文档使用collection.FindOne()函数,需要一个filter文档和一个可以将结果解码为其值的指针

?
1
2
3
4
5
6
7
var result sunshareboy
filter := bson.D{{"name","wanger"}}
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)

返回结果如下

Connected to MongoDB!
Found a single document: {Name:wanger Age:24 City:北京}
Connection to MongoDB closed.

查询多个文档

查询多个文档使用collection.Find()函数,这个函数会返回一个游标,可以通过他来迭代并解码文档,当迭代完成后,关闭游标

Find函数执行find命令并在集合中的匹配文档上返回Cursor。
filter参数必须是包含查询运算符的文档,并且可以用于选择结果中包括哪些文档。不能为零。空文档(例如bson.D {})应用于包含所有文档。
opts参数可用于指定操作的选项,例如我们可以设置只返回五条文档的限制(https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#Find)。

?
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
//定义返回文档数量
    findOptions := options.Find()
    findOptions.SetLimit(5)
    //定义一个切片存储结果
    var results []*sunshareboy
    //将bson.D{{}}作为一个filter来匹配所有文档
    cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
    if err != nil {
        log.Fatal(err)
    }
    //查找多个文档返回一个游标
    //遍历游标一次解码一个游标
    for cur.Next(context.TODO()) {
        //定义一个文档,将单个文档解码为result
        var result sunshareboy
        err := cur.Decode(&result)
        if err != nil {
            log.Fatal(err)
        }
        results = append(results, &result)
    }
    fmt.Println(result)
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
    //遍历结束后关闭游标
    cur.Close(context.TODO())
    fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)

返回结果如下

Connected to MongoDB!
{wanger 24 北京}
{张冬冬 29 成都}
{华仔 28 深圳}
{素心 24 甘肃}
{刘大仙 24 杭州}
Found multiple documents (array of pointers): &[0xc000266450 0xc000266510 0xc000266570 0xc0002665d0 0xc000266630]
Connection to MongoDB closed.

更新MongoDB文档
更新单个文档
更新单个文档使用collection.UpdateOne()函数,需要一个filter来匹配数据库中的文档,还需要使用一个update文档来更新操作

filter参数必须是包含查询运算符的文档,并且可以用于选择要更新的文档。不能为零。如果过滤器不匹配任何文档,则操作将成功,并且将返回MatchCount为0的UpdateResult。如果过滤器匹配多个文档,将从匹配的集合中选择一个,并且MatchedCount等于1。
update参数必须是包含更新运算符的文档(https://docs.mongodb.com/manual/reference/operator/update/),并且可以用于指定要对所选文档进行的修改。它不能为nil或为空。
opts参数可用于指定操作的选项。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
filter := bson.D{{"name","张冬冬"}}
//如果过滤的文档不存在,则插入新的文档
opts := options.Update().SetUpsert(true)
update := bson.D{
    {"$set", bson.D{
        {"city", "北京"}},
    }}
result, err := collection.UpdateOne(context.TODO(), filter, update,opts)
if err != nil {
    log.Fatal(err)
}
if result.MatchedCount != 0 {
    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
}
if result.UpsertedCount != 0 {
    fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID)
}

返回结果如下

Connected to MongoDB!
Matched 1 documents and updated 1 documents.
Connection to MongoDB closed.

更新多个文档

更新多个文档使用collection.UpdateOne()函数,参数与collection.UpdateOne()函数相同

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
filter := bson.D{{"city","北京"}}
//如果过滤的文档不存在,则插入新的文档
opts := options.Update().SetUpsert(true)
update := bson.D{
    {"$set", bson.D{
        {"city", "铁岭"}},
    }}
result, err := collection.UpdateMany(context.TODO(), filter, update,opts)
if err != nil {
    log.Fatal(err)
}
if result.MatchedCount != 0 {
    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
}
if result.UpsertedCount != 0 {
    fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID)
}

返回结果如下

Connected to MongoDB!
Matched 2 documents and updated 2 documents.
Connection to MongoDB closed.

删除MongoDB文档

可以使用collection.DeleteOne()collection.DeleteMany()删除文档。如果你传递bson.D{{}}作为过滤器参数,它将匹配数据集中的所有文档。还可以使用collection. drop()删除整个数据集。

?
1
2
3
4
5
6
filter := bson.D{{"city","铁岭"}}
deleteResult, err := collection.DeleteMany(context.TODO(), filter)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)

返回结果如下

Connected to MongoDB!
Deleted 2 documents in the trainers collection
Connection to MongoDB closed.

获取MongoDB服务状态

上面我们介绍了对MongoDB的CRUD,其实还支持很多对mongoDB的操作,例如聚合、事物等,接下来介绍一下使用golang获取MongoDB服务状态,执行后会返回一个bson.Raw类型的数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ctx, _ = context.WithTimeout(context.Background(), 30*time.Second)
serverStatus, err := client.Database("admin").RunCommand(
    ctx,
    bsonx.Doc{{"serverStatus", bsonx.Int32(1)}},
).DecodeBytes()
if err != nil {
    fmt.Println(err)
}
fmt.Println(serverStatus)
fmt.Println(reflect.TypeOf(serverStatus))
version, err := serverStatus.LookupErr("version")
fmt.Println(version.StringValue())
if err != nil {
    fmt.Println(err)
}

参考链接

https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial
https://godoc.org/go.mongodb.org/mongo-driver/mongo
从MongoDB中查询数据从MongoDB中查询数据从MongoDB中查询数据

到此这篇关于使用GO操作MongoDB的文章就介绍到这了,更多相关GO操作MongoDB内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/ithubb/p/16257722.html

延伸 · 阅读

精彩推荐
  • GolangGolang 语言极简 HTTP 客户端 GoRequest

    Golang 语言极简 HTTP 客户端 GoRequest

    GoRequest 是一个极简的 HTTP 客户端,作者灵感来源于 Node.js 库 SuperAgent。相比 Golang 标准库 net/http,GoRequest 使用起来更加简单。GoRequest 官方的口号是 “像机...

    Golang语言开发栈4392021-10-18
  • GolangGo语言string,int,int64 ,float之间类型转换方法

    Go语言string,int,int64 ,float之间类型转换方法

    Go语言中int类型和string类型都是属于基本数据类型,两种类型的转化都非常简单。下面通过本文给大家分享Go语言string,int,int64 ,float之间类型转换方法,感...

    哪来的查克拉42162020-05-07
  • GolangGo语言编程学习golang配置golint

    Go语言编程学习golang配置golint

    这篇文章主要为大家介绍了Go语言编程学习golang配置golint的过程示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职...

    秋天的春3532021-12-03
  • GolangGo语言里的new函数用法分析

    Go语言里的new函数用法分析

    这篇文章主要介绍了Go语言里的new函数用法,实例分析了new函数的功能及使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    脚本之家6112020-04-16
  • Golanggolang1.16新特性速览(推荐)

    golang1.16新特性速览(推荐)

    这篇文章主要介绍了golang1.16新特性速览,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    apocelipes6692021-03-29
  • Golanggolang int 转float 强转和高精度转操作

    golang int 转float 强转和高精度转操作

    这篇文章主要介绍了golang int 转float 强转和高精度转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    疯狂的鸭血8512021-03-14
  • GolangGo语言集成开发环境IDE详细安装教程

    Go语言集成开发环境IDE详细安装教程

    VSCode是免费开源的现代化轻量级代码编辑器,支持几乎所有主流的开发语言,内置命令行工具和 Git 版本控制系统,支持插件扩展,这篇文章主要介绍了G...

    Python小白进阶5632022-01-19
  • Golang详解Go 将在下个版本支持新型排序算法pdqsort

    详解Go 将在下个版本支持新型排序算法pdqsort

    这篇文章主要介绍了Go 将在下个版本支持新型排序算法:pdqsort,而就Go支持pdqsort算法,在HN上引起了不少的讨论,有人表示,我们研究排序算法这么久了,很...

    CSDN资讯3512022-09-27