关于golang:golang操作MongoDB总结

9次阅读

共计 5158 个字符,预计需要花费 13 分钟才能阅读完成。

下载安装 MongoDB

本文视频教程:https://www.bilibili.com/vide…

关注公众号,支付课程材料和源码

下载地址:

https://www.mongodb.com/download-center/community

关上客户端

mongo.exe

创立数据库

use go_db;

创立汇合

 db.createCollection("student");

下载安装驱动并连贯数据库

下载地址:

https://www.mongodb.com/download-center/community

关上客户端

mongo.exe

创立数据库

use go_db;

创立汇合

 db.createCollection("student");

下载驱动

go get github.com/mongodb/mongo-go-driver

连贯 mongoDB

package main

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


var client *mongo.Client

func initDB()  {
    // 设置客户端连贯配置
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    // 连贯到 MongoDB
    var err error
    client, err = mongo.Connect(context.TODO(), clientOptions)
    if err != nil {log.Fatal(err)
    }
    // 查看连贯
    err = client.Ping(context.TODO(), nil)
    if err != nil {log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
}

func main() {initDB()
}

运行后果

Connected to MongoDB!

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,须要先导入上面的包:

import "go.mongodb.org/mongo-driver/bson"

上面是一个应用 D 类型构建的 过滤器 文档的例子,它能够用来查找 name 字段与’张三’或’李四’匹配的文档:

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

Raw类型家族用于验证字节切片。你还能够应用 Lookup() 从原始类型检索单个元素。如果你不想要将 BSON 反序列化成另一种类型的开销,那么这是十分有用的。这个教程咱们将只应用 D 类型。

增加文档

创立一个构造体

type Student struct {
    Name string
    Age int
}

增加单个文档

应用 collection.InsertOne() 办法插入一条文档记录:

func insertOne(s Student) {initDB()
    collection := client.Database("go_db").Collection("student")
    insertResult, err := collection.InsertOne(context.TODO(), s)
    if err != nil {log.Fatal(err)
    }
    fmt.Println("Inserted a single document:", insertResult.InsertedID)
}

测试

func main() {s := Student{Name: "tom", Age: 20}
    insertOne(s)
}

运行后果

Connected to MongoDB!
Inserted a single document:  ObjectID("61124558682f5c9583330222")

客户端查看

mongodb 关上客户端
use go_db
db.student.find()
db.student.remove({}) // 删除所有

插入多个文档

应用 collection.InsertMany() 办法插入多条文档记录:

func insertMore(students []interface{}) {//students := []interface{}{s2, s3}
    initDB()
    collection := client.Database("go_db").Collection("student")
    insertManyResult, err := collection.InsertMany(context.TODO(), students)
    if err != nil {log.Fatal(err)
    }
    fmt.Println("Inserted multiple documents:", insertManyResult.InsertedIDs)
}

测试

func main() {s := Student{Name: "tom", Age: 20}
    s1 := Student{Name: "kite", Age: 21}
    s2 := Student{Name: "rose", Age: 22}
    students := []interface{}{s, s1, s2}
    insertMore(students)
}

运行后果

Connected to MongoDB!
Inserted multiple documents:  [ObjectID("611246c56637c3554426bc92") ObjectID("611246c56637c3554426bc93") ObjectID("611246c56637c3554426bc94")]

更多办法请查阅官网文档。

查找文档

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")

    co := options.Client().ApplyURI("mongodb://localhost:27017")
    mongo.Connect(context.TODO(), co)
    // 连贯到 MongoDB
    var err error
    client, err = mongo.Connect(context.TODO(), clientOptions)
    if err != nil {log.Fatal(err)
    }

    client.Ping(context.TODO(), nil)
    // 查看连贯
    err = client.Ping(context.TODO(), nil)
    if err != nil {log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
}

func find() {ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    collection := client.Database("go_db").Collection("student")
    cur, err := collection.Find(ctx, bson.D{})
    if err != nil {log.Fatal(err)
    }
    defer cur.Close(ctx)
    for cur.Next(ctx) {
        var result bson.D
        err := cur.Decode(&result)
        if err != nil {log.Fatal(err)
        }
        fmt.Printf("result: %v\n", result)
        fmt.Printf("result.Map(): %v\n", result.Map()["name"])
    }
    if err := cur.Err(); err != nil {log.Fatal(err)
    }
}



func main() {initDB()
    find()}

更新文档

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"
)

type Student struct {
    Name string
    Age  int
}

var client *mongo.Client

func initDb() {co := options.Client().ApplyURI("mongodb://localhost:27017")
    c, err := mongo.Connect(context.TODO(), co)
    if err != nil {log.Fatal(err)
    }

    err2 := c.Ping(context.TODO(), nil)
    if err2 != nil {log.Fatal(err2)
    } else {fmt.Println("连贯胜利!")
    }
    client = c
}

func update() {ctx := context.TODO()
    defer client.Disconnect(ctx)
    c := client.Database("go_db").Collection("Student")

    update := bson.D{{"$set", bson.D{{"Name", "big tom"}, {"Age", 22}}}}

    ur, err := c.UpdateMany(ctx, bson.D{{"name", "tom"}}, update)
    if err != nil {log.Fatal(err)
    }
    fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
}

func main() {initDb()
    update()}

删除文档

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"
)

type Student struct {
    Name string
    Age  int
}

var client *mongo.Client

func initDb() {co := options.Client().ApplyURI("mongodb://localhost:27017")
    c, err := mongo.Connect(context.TODO(), co)
    if err != nil {log.Fatal(err)
    }

    err2 := c.Ping(context.TODO(), nil)
    if err2 != nil {log.Fatal(err2)
    } else {fmt.Println("连贯胜利!")
    }
    client = c
}

func del() {initDb()
    c := client.Database("go_db").Collection("Student")
    ctx := context.TODO()

    dr, err := c.DeleteMany(ctx, bson.D{{"Name", "big kite"}})

    if err != nil {log.Fatal(err)
    }
    fmt.Printf("ur.ModifiedCount: %v\n", dr.DeletedCount)

}

func main() {del()
}
正文完
 0