可以免費試用 MongoDB ,500MB 平時做測試沒有問題啦,連接數據庫可能因為網絡有點慢,但是我們是測試啊,不在乎這點吧~
這是怎么申請試用版的博客,感謝這位大佬。注冊好用起來很方便~ 傳送門 https://www.cnblogs.com/xybaby/p/9460634.html
連接數據庫選擇的驅動是 mongo-go-driver , 傳送門 https://github.com/mongodb/mongo-go-driver/tree/master/examples/documentation_examples
具體操作是這樣的,在GOPATH,或者項目目錄下。
go get github.com/mongodb/mongo-go-driver/mongo
如果用的是 Go Modules 引入后會爆紅!所以我們需要 go mod tidy 。在國內你是知道的,所以我們這樣。
powershell $env:GOPROXY = "https://goproxy.io" go mod tidy
然后下面是代碼
建一個文件夾名字是 mgodb / mgo.go
package mgodb
import (
"context"
_"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
)
type mgo struct {
uri string //數據庫網絡地址
database string //要連接的數據庫
collection string //要連接的集合
}
func (m *mgo)Connect() *mongo.Collection {
ctx , cancel :=context.WithTimeout(context.Background(),10*time.Second)
defer cancel() //養成良好的習慣,在調用WithTimeout之后defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(m.uri))
if err != nil {
log.Print(err)
}
collection := client.Database(m.database).Collection(m.collection)
return collection
}
基本就是這樣連接了,下面我們來測試耗時在哪。 在當前文件夾創建 mgodb / mgo_test.go Goland會自動識別這是測試文件。代碼
package mgodb
import (
"fmt"
"testing"
)
func TestMgo_Connect(t *testing.T) {
var mgo = &mgo{
"mongodb+srv://user:password@官網給你的.mongodb.net",
"MainSite",
"UsersM12",
}
mgo.Connect()
//collection :=mgo.Connect()
//fmt.Printf("%T\n",collection)
}
可以直接在 Goland 里執行,但是在控制台功能更多。
在這里我們需要用到 Graphviz 繪圖軟件 ,記得在環境變量配置一下。 傳送門 : http://www.graphviz.org/
我們在命令行里執行測試文件
go test -bench . -cpuprofile cpu.out
這樣會生成可執行文件 mgodb.test.exe 和 cpu.out
go tool pprof cpu.out
這時會有一個交互界面在里面輸入 web
(pprof) web (pprof) exit
就可以打開這張圖片,svg 不能上傳,大概可以看出連接花費了630ms

大概就是這樣了,查詢的語法都在 github那個傳送門里,可以去看一下。
這是我現在使用的代碼可以參考一下。
在 和 mgodb 文件夾下 建一個 initDB.go 文件
package models
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
type Database struct {
Mongo * mongo.Client
}
var DB *Database
//初始化
func Init() {
DB = &Database{
Mongo: SetConnect(),
}
}
// 連接設置
func SetConnect() *mongo.Client{
uri := "mongodb+srv://用戶名:密碼@官方給的.mongodb.net"
ctx ,cancel := context.WithTimeout(context.Background(),10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx,options.Client().ApplyURI(uri).SetMaxPoolSize(20)) // 連接池
if err !=nil{
fmt.Println(err)
}
return client
}
mgodb 里的 mgo.db 現在的代碼是這樣的 使用起來比較簡單,刪除和插入文檔,只需要一個唯一匹配的鍵值對就可以了
package mgodb
import (
"blog/models"
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"strconv"
"time"
)
type mgo struct {
database string
collection string
}
func NewMgo(database, collection string) *mgo {
return &mgo{
database,
collection,
}
}
// 查詢單個
func (m *mgo) FindOne(key string, value interface{}) *mongo.SingleResult {
client := models.DB.Mongo
collection, _ := client.Database(m.database).Collection(m.collection).Clone()
//collection.
filter := bson.D{{key, value}}
singleResult := collection.FindOne(context.TODO(), filter)
return singleResult
}
//插入單個
func (m *mgo) InsertOne(value interface{}) *mongo.InsertOneResult {
client := models.DB.Mongo
collection := client.Database(m.database).Collection(m.collection)
insertResult, err := collection.InsertOne(context.TODO(), value)
if err != nil {
fmt.Println(err)
}
return insertResult
}
//查詢集合里有多少數據
func (m *mgo) CollectionCount() (string, int64) {
client := models.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) *mongo.Cursor {
client := models.DB.Mongo
collection := client.Database(m.database).Collection(m.collection)
SORT := bson.D{{"_id", sort}} //filter := bson.D{{key,value}}
filter := bson.D{{}}
findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
//findOptions.SetLimit(i)
temp, _ := collection.Find(context.Background(), filter, findOptions)
return temp
}
//獲取集合創建時間和編號
func (m *mgo) ParsingId(result string) (time.Time, uint64) {
temp1 := result[:8]
timestamp, _ := strconv.ParseInt(temp1, 16, 64)
dateTime := time.Unix(timestamp, 0) //這是截獲情報時間 時間格式 2019-04-24 09:23:39 +0800 CST
temp2 := result[18:]
count, _ := strconv.ParseUint(temp2, 16, 64) //截獲情報的編號
return dateTime, count
}
//刪除文章和查詢文章
func (m *mgo) DeleteAndFind(key string, value interface{}) (int64, *mongo.SingleResult) {
client := models.DB.Mongo
collection := client.Database(m.database).Collection(m.collection)
filter := bson.D{{key, value}}
singleResult := collection.FindOne(context.TODO(), filter)
DeleteResult, err := collection.DeleteOne(context.TODO(), filter, nil)
if err != nil {
fmt.Println("刪除時出現錯誤,你刪不掉的~")
}
return DeleteResult.DeletedCount, singleResult
}
//刪除文章
func (m *mgo) Delete(key string, value interface{}) int64 {
client := models.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 {
fmt.Println(err)
}
return count.DeletedCount
}
//刪除多個
func (m *mgo) DeleteMany(key string, value interface{}) int64 {
client := models.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 {
fmt.Println(err)
}
return count.DeletedCount
}
應該知道怎么初始化吧
文件結構是這樣的,models 在根目錄下

package main
func main() {
models.Init() //初始化數據庫
app := newApp()
routers.Router(app) // 頁面訪問
app.Run(iris.Addr(":3000")) // 火箭發射
}
