Golang 操作MongoDB连接池示例

Jackey Golang 3,836 次浏览 , 没有评论
package main

import (
    "context"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
    "time"
)

// MongoDB 连接池
var MongoDBClient *mongo.Database

// pool 连接池模式
func ConnectToDB() {
    user := "upon_dev"
    password := "Q9fxUzQrEAeVufuZ"
    host := "8.140.132.43"
    port := "27017"
    dbName := "upon_data_dev"
    timeOut := 2
    maxNum := 50

    uri := fmt.Sprintf("mongodb://%s:%s@%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 insert()  {
    ash := Trainer{"18954145016", "123456", []string{"abc1", "efg1", "hij1"}}
    insertResult, err := MongoDBClient.Collection("test").InsertOne(context.TODO(), ash)
    if err != nil {
        fmt.Println(err)
    }
    println("Inserted a single document: ", insertResult.InsertedID)
}

func find()  {
    findOptions := options.Find()
    findOptions.SetLimit(10)
    cur, err := MongoDBClient.Collection("test").Find(context.TODO(), bson.D{{"bssid", "abc1"}}, findOptions)
    if err != nil {
        fmt.Println(err)
    }
    var results []*Trainer
    for cur.Next(context.TODO()) {

        // create a value into which the single document can be decoded
        var elem Trainer
        err := cur.Decode(&elem)
        if err != nil {
            fmt.Println(err)
        }

        results = append(results, &elem)
    }

    if err := cur.Err(); err != nil {
        fmt.Println(err)
    }

    for _, v := range results {
        fmt.Println(v.Phone)
    }
}

type Trainer struct {
    Phone string
    Imei  string
    Bssid  []string
}

func main() {
    ConnectToDB()
    insert()
    find()
}
// find混合条件查询
func find() {
    findOptions := options.Find()
    findOptions.SetLimit(10)
    var mem service.Member
    mem.Bssid = []string{"a"}
    mem.Address = []string{"c"}
    //filter := bson.D{{"bssid", bson.D{{"$in", bson.A{"a"}}}}}
    //filter := bson.D{{"$or", bson.A{
    //	bson.D{{"bssid", bson.D{{"$in", mem.Bssid}}}},
    //	bson.D{{"address", bson.D{{"$in", mem.Address}}}},
    //}}}
    //filter := bson.D{{
    //	"gender", bson.D{{"$in", bson.A{1,2}}},
    //}}
    filter := bson.D{{
        "$and", bson.A{
            bson.D{{
                "gender", bson.D{{"$in", bson.A{1,2}}},
            }},
            bson.D{{"$or", bson.A{
                bson.D{{"bssid", bson.D{{"$in", mem.Bssid}}}},
                bson.D{{"address", bson.D{{"$in", mem.Address}}}},
            }}},
        },
    }}
    cur, err := MongoDBClient.Collection("da_member").Find(context.TODO(), filter, findOptions)
    if err != nil {
        fmt.Println(err)
    }
    if err = cur.Err(); err != nil {
        fmt.Println(err)
    }
    var results []*service.Member
    err = cur.All(context.TODO(), &results)
    if err != nil {
        fmt.Println(err)
    }
    for _, v := range results {
        fmt.Println(*v.Mobile)
    }
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go