一、前言

     以前一直用着的"gopkg.in/mgo.v2"已经有日子没有人维护了,官方推出了mongo的golang driver,今天有空来看看。

 

二、驱动包获取

"go.mongodb.org/mongo-driver/bson"    //BOSN解析包
"go.mongodb.org/mongo-driver/mongo"    //MongoDB的Go驱动包
"go.mongodb.org/mongo-driver/mongo/options"

三、数据库连接

1. 连接数据库,获取数据库的总大小

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	// Rest of the code will go here
	// Set client options 设置连接参数
	clientOptions := options.Client().ApplyURI("mongodb://root:xxxxxxxxxxxxxxxxxxxxxxx@172.20.52.158:41134/?connect=direct;authSource=admin") # connect=direct这个参数设置是副本集我只连接其中一个主节点

	// 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!")

	databases, err := client.ListDatabases(context.TODO(), bson.M{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(databases.TotalSize / 1024 / 1024 / 1024)
	err = client.Disconnect(context.TODO())

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

}

四、CRUD操作

一旦你已经连接到一个数据库, 是时候添加和操作一些数据了。集合类型有一些函数允许你给数据库发送查询。

1. 插入文档

首先, 创建一些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)

2.更新文档

collection.UpdateOne()函数允许你更新单一的文档, 它需要一个filter文档来匹配数据库里面的文档, 并且需要一个update文档来描述更新的操作。你可以用bson.D类型来构建这些文档:

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

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

这段代码会匹配name是“Ash”的文档, 并且将Ash的age增加1 —生日快乐, Ash!

updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

3. 查找文档

要查询一个文档, 你需要一个filter文档, 以及一个指针在它里边保存结果的解码。要查询单个的文档, 使用collection.FindOne()函数。这个函数返回单个的结果,被解码成为一个值。你可以使用和上面使用过的update查询一样的filter变量来匹配一个name是Ash的文档。

// create a value into which the result can be decoded
var result Trainer

err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Found a single document: %+v\n", result)

要查询多个文档, 使用collection.Find(),这个函数返回一个游标。一个游标提供一个文档流, 通过它你可以遍历和解码每一个文档。一旦一个游标被消耗掉, 你应该关闭游标。这里你也可以使用options包来设定一些操作选项, 特别的, 你可以设定一个返回文档数量的限制, 比如2个。

// Pass these options to the Find method
findOptions := options.Find()
findOptions.SetLimit(2)

// Here's an array in which you can store the decoded documents
var results []*Trainer

// Passing bson.D{{}} as the filter matches all documents in the collection
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
if err != nil {
    log.Fatal(err)
}

// Finding multiple documents returns a cursor
// Iterating through the cursor allows us to decode documents one at a time
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 {
        log.Fatal(err)
    }

    results = append(results, &elem)
}

if err := cur.Err(); err != nil {
    log.Fatal(err)
}

// Close the cursor once finished
cur.Close(context.TODO())

fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)

4.删除文档

最后, 你可以使用collection.DeleteOne() 或者 collection.DeleteMany()来删除文档。这里, 你传递bson.D{{}}作为filter参数, 这会匹配集合内所有的文档。 你也可以使用collection.Drop()来删除整个集合。

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)

 

五、参考文章

Mongo-Driver驱动包官方文档
BSON包官方文档
mongo包官方文档
options包官方文档

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐