关于mongodb:Go-操作mongodb

34次阅读

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

增加 mongodb 驱动程序

用于 go get 将 Go 驱动程序增加为依赖项。

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

应用办法

创立 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:%[email protected]%s:%s/%s?w=majority", user, password, host, port, dbName)
    // 设置连贯超时工夫
    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeOut))
    defer cancel()
    // 通过传进来的 uri 连贯相干的配置
    o := options.Client().ApplyURI(uri)
    // 设置最大连接数 - 默认是 100,不设置就是最大 max 64
    o.SetMaxPoolSize(uint64(maxNum))
    // 发动链接
    client, err := mongo.Connect(ctx, o)
    if err != nil {fmt.Println("ConnectToDB", err)
        return
    }
    // 判断服务是不是可用
    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:[email protected]: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)
}

// 插入单条数据
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)
}

// 插入多条数据
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)

}

// 查问多条数据
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)
}

// 删除单个文件
func deleteOne() {filter := bson.D{{"phone", "16666666666"}}
    result, err := MongoDBClient.Collection("test1").DeleteOne(context.TODO(), filter)
    if err != nil {panic(err)
    }
    fmt.Println(result)
}

// 删除多个
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() {
    // 连贯数据库
    ConnectToDB()
    // 连接池连贯数据库
    //ConnectToDBPool()
    // 插入单条数据
    //insertOne()
    // 插入多条数据
    //insert()
    // 查找单条数据
    //findOne()
    // 查找多条数据
    find()
    // 批改单条数据
    //updateOne()
    // 批改多条数据
    //update()
    // 替换文档
    //replaceOne()
    // 删除多个
    //deleteOne()
    // 删除多个
    //delete()}

links

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

  • 目录
  • 上一节:
  • 下一节:

正文完
 0