go mongodb详解

导入数据库驱动

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

连接

// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)

if err != nil {
    log.Fatal(err)
}

// Check the connection
err = client.Ping(context.TODO(), nil)

if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

或:

credential := options.Credential{
    Username: "user",
    Password: "password",
}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential)
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
    log.Fatal(err)
}
_ = client

关闭连接

err = client.Disconnect(context.TODO())

if err != nil {
    log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")

BSON使用

JSON文档在MongoDB里面以二进制形式存储,被称作BSON(二进制编码的JSON)。不像其他的数据库保存JSON数据为简单的字符串和数字, BSON扩展了JSON的保存形式, 包括额外的类型, 比如int, long, date, floating point以及decimal128。这使得它让应用程序更容易来可靠地处理、排序和比较数据。

插入文档

//创建一些Trainer结构体用来插入到数据库
ash := Trainer{"Ash", 10, "Pallet Town"}
misty := Trainer{"Misty", 10, "Cerulean City"}
brock := Trainer{"Brock", 15, "Pewter City"}

//插入一个单独的文档, 使用 collection.InsertOne()函数:
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)

//同时插入多个文档, collection.InsertMany() 函数会采用一个slice对象
trainers := []interface{}{misty, brock}
insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)

更新文档

filter := bson.D{{"name", "Ash"}}

update := bson.D{
    {"$inc", bson.D{
        {"age", 1},
    }},
}

//这段代码会匹配name是“Ash”的文档
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
    log.Fatal(err)
}

查找文档

删除文档

//你可以使用collection.DeleteOne() 或者 collection.DeleteMany()来删除文档。
deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)

实例

package main

import (
    "context"
    "log"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
    "go.mongodb.org/mongo-driver/x/bsonx"
)

type Book struct {
    Id       primitive.ObjectID `bson:"_id"`
    Name     string
    Category string
    Weight   int
    Author   AuthorInfo
}

type AuthorInfo struct {
    Name    string
    Country string
}

const (
    categoryComputer = "计算机"
    categorySciFi    = "科幻"
    countryChina     = "中国"
    countryAmerica   = "美国"
)

var (
    books = []interface{}{
        &Book{
            Id:       primitive.NewObjectID(),
            Name:     "深入理解计算机操作系统",
            Category: categoryComputer,
            Weight:   1,
            Author: AuthorInfo{
                Name:    "兰德尔 E.布莱恩特",
                Country: countryAmerica,
            },
        },
        &Book{
            Id:       primitive.NewObjectID(),
            Name:     "深入理解Linux内核",
            Category: categoryComputer,
            Weight:   1,
            Author: AuthorInfo{
                Name:    "博韦,西斯特",
                Country: countryAmerica,
            },
        },
        &Book{
            Id:       primitive.NewObjectID(),
            Name:     "三体",
            Category: categorySciFi,
            Weight:   1,
            Author: AuthorInfo{
                Name:    "刘慈欣",
                Country: countryChina,
            },
        },
    }
)

func main() {
    log.SetFlags(log.Llongfile | log.LstdFlags)

    opts := options.Client().ApplyURI("mongodb://localhost:27017")

    // 连接数据库
    client, err := mongo.Connect(context.Background(), opts)
    if err != nil {
        log.Fatal(err)
    }

    // 判断服务是不是可用
    if err = client.Ping(context.Background(), readpref.Primary()); err != nil {
        log.Fatal(err)
    }

    // 获取数据库和集合
    collection := client.Database("mydb").Collection("book")

    // 清空文档
    err = collection.Drop(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    // 设置索引
    idx := mongo.IndexModel{
        Keys:    bsonx.Doc{{"name", bsonx.Int32(1)}},
        Options: options.Index().SetUnique(true),
    }
    idxRet, err := collection.Indexes().CreateOne(context.Background(), idx)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.Indexes().CreateOne:", idxRet)

    // 插入一条数据
    insertOneResult, err := collection.InsertOne(context.Background(), books[0])
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.InsertOne: ", insertOneResult.InsertedID)

    // 插入多条数据
    insertManyResult, err := collection.InsertMany(context.Background(), books[1:])
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.InsertMany: ", insertManyResult.InsertedIDs)

    // 获取数据总数
    count, err := collection.CountDocuments(context.Background(), bson.D{})
    if err != nil {
        log.Fatal(count)
    }
    log.Println("collection.CountDocuments:", count)

    // 查询单条数据
    var one Book
    err = collection.FindOne(context.Background(), bson.M{"name": "三体"}).Decode(&one)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.FindOne: ", one)

    // 查询多条数据(方式一)
    cur, err := collection.Find(context.Background(), bson.D{})
    if err != nil {
        log.Fatal(err)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
    var all []*Book
    err = cur.All(context.Background(), &all)
    if err != nil {
        log.Fatal(err)
    }
    cur.Close(context.Background())

    log.Println("collection.Find curl.All: ", all)
    for _, one := range all {
        log.Println(one)
    }

    // 查询多条数据(方式二)
    cur, err = collection.Find(context.Background(), bson.D{})
    if err != nil {
        log.Fatal(err)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
    for cur.Next(context.Background()) {
        var b Book
        if err = cur.Decode(&b); err != nil {
            log.Fatal(err)
        }
        log.Println("collection.Find cur.Next:", b)
    }
    cur.Close(context.Background())

    // 模糊查询
    cur, err = collection.Find(context.Background(), bson.M{"name": primitive.Regex{Pattern: "深入"}})
    if err != nil {
        log.Fatal(err)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
    for cur.Next(context.Background()) {
        var b Book
        if err = cur.Decode(&b); err != nil {
            log.Fatal(err)
        }
        log.Println("collection.Find name=primitive.Regex{深入}: ", b)
    }
    cur.Close(context.Background())

    // 二级结构体查询
    cur, err = collection.Find(context.Background(), bson.M{"author.country": countryChina})
    // cur, err = collection.Find(context.Background(), bson.D{bson.E{"author.country", countryChina}})
    if err != nil {
        log.Fatal(err)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
    for cur.Next(context.Background()) {
        var b Book
        if err = cur.Decode(&b); err != nil {
            log.Fatal(err)
        }
        log.Println("collection.Find author.country=", countryChina, ":", b)
    }
    cur.Close(context.Background())

    // 修改一条数据
    b1 := books[0].(*Book)
    b1.Weight = 2
    update := bson.M{"$set": b1}
    updateResult, err := collection.UpdateOne(context.Background(), bson.M{"name": b1.Name}, update)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.UpdateOne:", updateResult)

    // 修改一条数据,如果不存在则插入
    new := &Book{
        Id:       primitive.NewObjectID(),
        Name:     "球状闪电",
        Category: categorySciFi,
        Author: AuthorInfo{
            Name:    "刘慈欣",
            Country: countryChina,
        },
    }
    update = bson.M{"$set": new}
    updateOpts := options.Update().SetUpsert(true)
    updateResult, err = collection.UpdateOne(context.Background(), bson.M{"_id": new.Id}, update, updateOpts)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.UpdateOne:", updateResult)

    // 删除一条数据
    deleteResult, err := collection.DeleteOne(context.Background(), bson.M{"_id": new.Id})
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.DeleteOne:", deleteResult)
}
# mongodb  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×