最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Go操作mongodb數(shù)據(jù)庫方法示例

 更新時(shí)間:2023年09月04日 11:31:01   作者:guyan0319  
這篇文章主要為大家介紹了Go操作mongodb數(shù)據(jù)庫方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

添加mongodb驅(qū)動(dòng)程序

用于go get將 Go 驅(qū)動(dòng)程序添加為依賴項(xiàng)。

go get go.mongodb.org/mongo-driver/mongo

使用方法

創(chuàng)建main.go 文件

package main
import (
    "context"
    "fmt"
    "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"
    "log"
    "time"
)
// MongoDB 連接池
var MongoDBClient *mongo.Database
// pool 連接池模式
func ConnectToDBPool() {
    user := "admin"
    password := "12345678"
    host := "127.0.0.1"
    port := "27017"
    dbName := "demo"
    timeOut := 2
    maxNum := 50
    uri := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?w=majority", user, password, host, port, dbName)
    // 設(shè)置連接超時(shí)時(shí)間
    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeOut))
    defer cancel()
    // 通過傳進(jìn)來的uri連接相關(guān)的配置
    o := options.Client().ApplyURI(uri)
    // 設(shè)置最大連接數(shù) - 默認(rèn)是100 ,不設(shè)置就是最大 max 64
    o.SetMaxPoolSize(uint64(maxNum))
    // 發(fā)起鏈接
    client, err := mongo.Connect(ctx, o)
    if err != nil {
        fmt.Println("ConnectToDB", err)
        return
    }
    // 判斷服務(wù)是不是可用
    if err = client.Ping(context.Background(), readpref.Primary()); err != nil {
        fmt.Println("ConnectToDB", err)
        return
    }
    // 返回 client
    MongoDBClient = client.Database(dbName)
}
func ConnectToDB() {
    clientOptions := options.Client().ApplyURI("mongodb://admin:12345678@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!")
    // 返回 client
    MongoDBClient = client.Database("demo")
    //defer client.Disconnect(ctx)
}
// 插入單條數(shù)據(jù)
func insertOne() {
    ash := Member{"13212345678", "123456", []string{"abc1", "efg1", "hij1"}}
    insertResult, err := MongoDBClient.Collection("test1").InsertOne(context.TODO(), ash)
    if err != nil {
        fmt.Println(err)
    }
    println("Inserted a single document: ", insertResult.InsertedID)
}
// 插入多條數(shù)據(jù)
func insert() {
    var ash []interface{}
    ash = append(ash, Member{"13222222222", "123456", []string{"aaa", "bbb", "ccc"}})
    ash = append(ash, Member{"13333333333", "123456", []string{"aaa1", "bbb1", "ccc1"}})
    fmt.Println(ash)
    insertResult, err := MongoDBClient.Collection("test1").InsertMany(context.TODO(), ash)
    if err != nil {
        fmt.Println(err)
    }
    println("Inserted Multiple document: ", insertResult.InsertedIDs)
}
// 查詢單條
func findOne() {
    var result bson.M
    err := MongoDBClient.Collection("test1").FindOne(context.TODO(), bson.D{{"info", "aaa1"}}).Decode(&result)
    if err != nil {
        if err == mongo.ErrNoDocuments {
            //This error means your query did not match any documents.
            return
        }
        panic(err)
    }
    fmt.Println(result)
}
// 查詢多條數(shù)據(jù)
func find() {
    findOptions := options.Find()
    findOptions.SetLimit(10)
    cur, err := MongoDBClient.Collection("test1").Find(context.TODO(), bson.D{{"phone", "13333333333"}}, findOptions)
    if err != nil {
        fmt.Println(err)
    }
    var results []*Member
    for cur.Next(context.TODO()) {
        // create a value into which the single document can be decoded
        var elem Member
        err := cur.Decode(&elem)
        if err != nil {
            fmt.Println(err)
        }
        results = append(results, &elem)
    }
    if err := cur.Err(); err != nil {
        fmt.Println(err)
    }
    //fmt.Println(results)
    for _, v := range results {
        fmt.Println(v.Phone)
        fmt.Println(v.Name)
        fmt.Println(v.Info)
    }
}
func updateOne() {
    //如果過濾的文檔不存在,則插入新的文檔
    opts := options.Update().SetUpsert(true)
    id, _ := primitive.ObjectIDFromHex("633b02b6e082e5046001d0b9")
    filter := bson.D{{"_id", id}}
    update := bson.D{{"$set", bson.D{{"phone", "1444444444444"}}}}
    result, err := MongoDBClient.Collection("test1").UpdateOne(context.TODO(), filter, update, opts)
    //result, err := MongoDBClient.Collection("test1").UpdateOne(context.TODO(), filter, update)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
func update() {
    filter := bson.D{{"name", "123456"}}
    update := bson.D{{"$set", bson.D{{"name", "張三"}}}}
    result, err := MongoDBClient.Collection("test1").UpdateMany(context.TODO(), filter, update)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
// 替換文檔
func replaceOne() {
    filter := bson.D{{"phone", "13222222222"}}
    replacement := bson.D{{"phone", "16666666666"}}
    result, err := MongoDBClient.Collection("test1").ReplaceOne(context.TODO(), filter, replacement)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
// 刪除單個(gè)文件
func deleteOne() {
    filter := bson.D{{"phone", "16666666666"}}
    result, err := MongoDBClient.Collection("test1").DeleteOne(context.TODO(), filter)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
// 刪除多個(gè)
func delete() {
    //filter := bson.D{{"runtime", bson.D{{"$gt", 800}}}}
    filter := bson.D{{"phone", "16666666666"}}
    results, err := MongoDBClient.Collection("test1").DeleteMany(context.TODO(), filter)
    if err != nil {
        panic(err)
    }
    fmt.Println(results)
}
type Member struct {
    Phone string
    Name  string
    Info  []string
}
func main() {
    //連接數(shù)據(jù)庫
    ConnectToDB()
    //連接池連接數(shù)據(jù)庫
    //ConnectToDBPool()
    //插入單條數(shù)據(jù)
    //insertOne()
    //插入多條數(shù)據(jù)
    //insert()
    //查找單條數(shù)據(jù)
    //findOne()
    //查找多條數(shù)據(jù)
    find()
    //修改單條數(shù)據(jù)
    //updateOne()
    //修改多條數(shù)據(jù)
    //update()
    //替換文檔
    //replaceOne()
    // 刪除多個(gè)
    //deleteOne()
    // 刪除多個(gè)
    //delete()
}

links https://www.mongodb.com/docs/...

以上就是Go操作mongodb數(shù)據(jù)庫方法示例的詳細(xì)內(nèi)容,更多關(guān)于Go操作mongodb的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Go語言封裝一個(gè)Cron定時(shí)任務(wù)管理器

    Go語言封裝一個(gè)Cron定時(shí)任務(wù)管理器

    在現(xiàn)代應(yīng)用中,定時(shí)任務(wù)是非常常見的需求,無論是用于定時(shí)清理數(shù)據(jù),還是定時(shí)執(zhí)行系統(tǒng)維護(hù)任務(wù),下面我們就來使用Go語言封裝一個(gè)Cron定時(shí)任務(wù)管理器吧
    2024-12-12
  • Go語言結(jié)合Gin框架快速實(shí)現(xiàn)分頁查詢接口

    Go語言結(jié)合Gin框架快速實(shí)現(xiàn)分頁查詢接口

    在開發(fā)?Web?應(yīng)用時(shí),分頁查詢?是非常常見的需求,在?Go?語言中,我們可以結(jié)合?GORM?+?Gin?框架,快速實(shí)現(xiàn)分頁查詢接口,下面我們來看看具體實(shí)現(xiàn)方法吧
    2025-08-08
  • gin框架Context如何獲取Get?Query?Param函數(shù)數(shù)據(jù)

    gin框架Context如何獲取Get?Query?Param函數(shù)數(shù)據(jù)

    這篇文章主要為大家介紹了gin框架Context?Get?Query?Param函數(shù)獲取數(shù)據(jù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • Golang多個(gè)域名的跨域資源共享的實(shí)現(xiàn)

    Golang多個(gè)域名的跨域資源共享的實(shí)現(xiàn)

    本文主要介紹了Golang多個(gè)域名的跨域資源共享的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-02-02
  • 解析golang 標(biāo)準(zhǔn)庫template的代碼生成方法

    解析golang 標(biāo)準(zhǔn)庫template的代碼生成方法

    這個(gè)項(xiàng)目的自動(dòng)生成代碼都是基于 golang 的標(biāo)準(zhǔn)庫 template 的,所以這篇文章也算是對(duì)使用 template 庫的一次總結(jié),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2021-11-11
  • PHP和GO對(duì)接ChatGPT實(shí)現(xiàn)聊天機(jī)器人效果實(shí)例

    PHP和GO對(duì)接ChatGPT實(shí)現(xiàn)聊天機(jī)器人效果實(shí)例

    這篇文章主要為大家介紹了PHP和GO對(duì)接ChatGPT實(shí)現(xiàn)聊天機(jī)器人效果實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • go?Cobra命令行工具入門教程

    go?Cobra命令行工具入門教程

    Cobra是一個(gè)用Go語言實(shí)現(xiàn)的命令行工具并且現(xiàn)在正在被很多項(xiàng)目使用,例如:Kubernetes、Hugo和Github?CLI等,通過使用Cobra,我們可以快速的創(chuàng)建命令行工具,特別適合寫測(cè)試腳本,各種服務(wù)的Admin?CLI等,本文重點(diǎn)給大家介紹go?Cobra命令行工具,感興趣的朋友一起看看吧
    2022-06-06
  • 解讀go在遍歷map過程中刪除成員是否安全

    解讀go在遍歷map過程中刪除成員是否安全

    在Go語言中,通過for range遍歷map時(shí)可以安全地刪除當(dāng)前遍歷到的元素,因?yàn)楸闅v過程中的刪除操作不會(huì)影響遍歷的進(jìn)行,但需要注意,遍歷順序是不確定的,刪除元素不會(huì)導(dǎo)致程序錯(cuò)誤,但可能會(huì)影響剩余元素的遍歷順序,在多線程環(huán)境下
    2024-09-09
  • logrus hook輸出日志到本地磁盤的操作

    logrus hook輸出日志到本地磁盤的操作

    這篇文章主要介紹了logrus hook輸出日志到本地磁盤的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • Go實(shí)現(xiàn)List、Set、Stack、Deque等數(shù)據(jù)結(jié)構(gòu)的操作方法

    Go實(shí)現(xiàn)List、Set、Stack、Deque等數(shù)據(jù)結(jié)構(gòu)的操作方法

    Go語言團(tuán)隊(duì)的一個(gè)核心目標(biāo)是保持語言的簡(jiǎn)單性,他們認(rèn)為,如果一個(gè)功能可以用簡(jiǎn)單的組合來實(shí)現(xiàn),那就沒有必要把它放進(jìn)標(biāo)準(zhǔn)庫里,本文給大家介紹Go實(shí)現(xiàn)List、Set、Stack、Deque等數(shù)據(jù)結(jié)構(gòu)的操作方法,感興趣的朋友跟隨小編一起看看吧
    2024-12-12

最新評(píng)論

祁连县| 荥经县| 江山市| 宁陕县| 葫芦岛市| 贡觉县| 西畴县| 通化市| 永胜县| 马鞍山市| 尼勒克县| 济源市| 时尚| 枣阳市| 比如县| 双辽市| 太仓市| 东台市| 莱州市| 仙桃市| 涪陵区| 丹巴县| 邵阳县| 古浪县| 寿阳县| 新巴尔虎右旗| 松潘县| 孟连| 依安县| 永和县| 乐都县| 政和县| 南漳县| 白沙| 平江县| 任丘市| 永登县| 纳雍县| 长岛县| 宜良县| 宁国市|