Go mongo driver使用

通过go mod下载官方driver包go.mongodb.org/mongo-driver

一、初始化设置

创建init.go

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

type Database struct {
    Mongo *mongo.Client
}

var DB *Database

//初始化
func Init(mongoUrl string) {
    DB = &Database{
        Mongo: SetConnect(mongoUrl),
    }
}

//连接设置
func SetConnect(mongoUrl string) *mongo.Client {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    // 连接池
    client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoUrl).SetMaxPoolSize(20))
    if err != nil {
        log.Println(err)
    }
    return client
}

二、 创建数据库连接信息对象

type mgo struct {
    database   string
    collection string
}

func NewMgo(database, collection string) *mgo {
    return &mgo{
        database,
        collection,
    }
}

三、CURD使用

创建mongoUtils.go

1. 插入文档

//插入单个文档
func (m *mgo) InsertOne(value interface{}) *mongo.InsertOneResult {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    insertResult, err := collection.InsertOne(context.TODO(), value)
    if err != nil {
        log.Fatal(err)
    }
    return insertResult
}

//插入多个文档
func (m *mgo) InsertMany(values []interface{}) *mongo.InsertManyResult {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    result, err := collection.InsertMany(context.TODO(), values)
    if err != nil {
        log.Fatal(err)
    }
    return result
}

2. 删除文档

//删除文档
func (m *mgo) Delete(key string, value interface{}) int64 {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    filter := bson.D{{key, value}}
    count, err := collection.DeleteOne(context.TODO(), filter, nil)
    if err != nil {
        log.Fatal(err)
    }
    return count.DeletedCount
}

//删除多个文档
func (m *mgo) DeleteMany(key string, value interface{}) int64 {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    filter := bson.D{{key, value}}

    count, err := collection.DeleteMany(context.TODO(), filter)
    if err != nil {
        log.Fatal(err)
    }
    return count.DeletedCount
}

3. 更新文档

//更新单个文档
func (m *mgo) UpdateOne(filter, update interface{}) int64 {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    result, err := collection.UpdateOne(context.TODO(), filter, update)
    if err != nil {
        log.Fatal(err)
    }
    return result.UpsertedCount
}

//更新多个文档
func (m *mgo) UpdateMany(filter, update interface{}) int64 {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    result, err := collection.UpdateMany(context.TODO(), filter, update)
    if err != nil {
        log.Fatal(err)
    }
    return result.UpsertedCount
}

4.查询文档

// 查询单个文档
func (m *mgo) FindOne(key string, value interface{}) *mongo.SingleResult {
    client := DB.Mongo
    collection, e := client.Database(m.database).Collection(m.collection).Clone()
    if e != nil {
        log.Fatal(e)
    }
    filter := bson.D{{key, value}}
    singleResult := collection.FindOne(context.TODO(), filter)
    return singleResult
}

//查询多个文档
func (m *mgo) FindMany(filter interface{}) (*mongo.Cursor, error) {
    client := DB.Mongo
    collection, e := client.Database(m.database).Collection(m.collection).Clone()
    if e != nil {
        log.Fatal(e)
    }
    return collection.Find(context.TODO(), filter)
}
//多条件查询
func (m *mgo) FindManyByFilters(filter interface{}) (*mongo.Cursor, error) {
    client := DB.Mongo
    collection, e := client.Database(m.database).Collection(m.collection).Clone()
    if e != nil {
        log.Fatal(e)
    }
    return collection.Find(context.TODO(), bson.M{"$and": filter})
}

//查询集合里有多少数据
func (m *mgo) CollectionCount() (string, int64) {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    name := collection.Name()
    size, _ := collection.EstimatedDocumentCount(context.TODO())
    return name, size
}

//按选项查询集合
// Skip 跳过
// Limit 读取数量
// sort 1 ,-1 . 1 为升序 , -1 为降序
func (m *mgo) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) *mongo.Cursor {
    client := DB.Mongo
    collection := client.Database(m.database).Collection(m.collection)
    SORT := bson.D{{"_id", sort}}
    filter := bson.D{{key, value}}
    findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
    temp, _ := collection.Find(context.Background(), filter, findOptions)
    return temp
}

方法调用测试

import (
    "context"
    "go.mongodb.org/mongo-driver/bson"
    "log"
    "sltily-utils/mongo"
)

func main() {
    mongo.Init("mongodb://localhost:27017")
    mgo := mongo.NewMgo("test", "test")
    var query []bson.M
    typeFilter := bson.M{"type": "go"}
    query = append(query, typeFilter)
    startTimeFilter := bson.M{"updateTimestamp": bson.M{"$gte": 0}}
    query = append(query, startTimeFilter)
    endTimeFilter := bson.M{"updateTimestamp": bson.M{"$lte": 1574870400000}}
    query = append(query, endTimeFilter)
    cursor, e := mgo.FindManyByFilters(query)
    if e != nil {
        log.Fatal(e)
    }
    for cursor.Next(context.TODO()) {
        println(cursor.Current.String())
    }
}

参考: MongoDB Go Driver Tutorial

你可能感兴趣的:(Go mongo driver使用)