可以免费试用 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")) // 火箭发射
}

最新文章

  1. iOS 9学习系列:打通 iOS 9 的通用链接(Universal Links)
  2. SpringMVC学习笔记(四)
  3. 【整理】--【字符设备】分配设备号register_chrdev_region()、alloc_chrdev_region() 和 register_chrdev()
  4. js-小效果-无缝滚动
  5. 【原】训练自己haar-like特征分类器并识别物体(2)
  6. eclipse 利用已有c++代码建工程,并编译执行
  7. CSS经典布局-圣杯布局、双飞翼布局
  8. 在JavaScript中使用json.js:Ajax项目之GET请求(同步)
  9. lsdyna进阶教程-弹性球撞击刚性平板
  10. mock打桩之EasyMock
  11. 全文检索-Elasticsearch (三) DSL
  12. npm 常规错误
  13. pymysql操作mysql
  14. java解析Json字符串之懒人大法
  15. selec2组件使用方法
  16. c# 集合中有数字、字符的Orderby排序
  17. Java - 20 Java 继承
  18. h5 微信分享朋友和朋友圈
  19. AsyncHttpClient的连接池使用逻辑
  20. iOS block分析

热门文章

  1. [置顶] 都是类型惹的祸——小心unsigned
  2. 【转】onclick事件与href='javascript:function()'的区别
  3. SqlServer——存储过程(未完工)
  4. windows下查看端口占用(砖)
  5. DAY17-Django之logging
  6. JDBC连接MYSQL,批量执行SQL语句或在执行一个SQL语句之前执行一个SQL语句
  7. Python单例模式剖析
  8. python笔记--5--文件操作
  9. go语言linux环境配置
  10. Maven 导包后,在Maven Dependencies 里面却没有相应的包