安装MongoDB驱动程序

mkdr mongodb 
cd mongodb 
go mod init  
go get go.mongodb.org/mongo-driver/mongo

连接MongoDB

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

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格式为

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

单机版

mongodb://localhost:27017

副本集

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

分片集群

mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017
context.TODO()
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)

列出所有数据库

databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
   log.Fatal(err)
}
fmt.Println(databases)

在GO中使用BSON对象

Raw系列D
//定义插入数据的结构体
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)

执行结果如下  
![](https://s4.51cto.com/images/blog/202011/07/378adacb26314b3532fa8947e3516fc1.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
#### 同时插入多条文档
```go
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文档和一个可以将结果解码为其值的指针

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()函数,这个函数会返回一个游标,可以通过他来迭代并解码文档,当迭代完成后,关闭游标

//定义返回文档数量
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.
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()函数相同

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()
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类型的数据

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