博客:https://hzeyuan.cn


以前用的python,操作数据库用的是mongoengine,现在换成了go,发现了一个也挺不错的操作mongoDB驱动,mgo!

示例github地址:https://github.com/hzeyuan/learnGO/tree/master/mgo-examples


1.mgo的安装

go get gopkg.in/mgo.v2

github地址: https://github.com/go-mgo/mgo 如今已经停止维护了!

2. 下面是一些实际遇到的一些基本操作

2.0

开始前定义一些基本的变量

  • Posts结构体代表我们要存储的文章,
  • Seession:连接上mongo
  • Databse:是我们要创建的数据库名称
  • Collection:是我们创建的集合名称
type Posts struct {Title stringContent stringDate time.Time
}var (Session,_ = mgo.Dial("localhost")Database = "mgo"Collection = "posts"Coll = Session.DB(Database).C(Collection)
)

2.1 删除数据库

// Drop Database
func DropDatebase(){fmt.Println("drop Database -->")if err :=Session.DB(Database).DropDatabase();err!=nil{fmt.Println("drop Datebase fail!!")}
}

2.2 添加一个文档

// 添加一个文档
func TestInsert(){fmt.Println("insert document to mongo DB -->")post1 := &Posts{Title:   "post1",Content: "post1-content",Date:    time.Now(),}Coll.Insert(post1)
}

2.3 添加多个文档

// 添加多个文档
func TestMultipleInsert(){t:=time.Now()fmt.Println("insert Multi document -->")var multiPosts []interface{}for i:=1;i<5001;i++{multiPosts = append(multiPosts,&Posts{Title:   fmt.Sprintf("post-%d",i),Content: fmt.Sprintf("post-%d-content",i),Date:    time.Now(),})}Coll.Insert(multiPosts...)fmt.Println(time.Since(t))
}

2.4 批量插入多个文档

//批量插入
func TestBulkInsert(){t:=time.Now()fmt.Println("Bulk Insert -->")b :=Coll.Bulk()var bulkPosts []interface{}for i:=10;i<5010;i++{bulkPosts = append(bulkPosts,&Posts{Title:   fmt.Sprintf("post-%d",i),Content: fmt.Sprintf("post-%d-content",i),Date:    time.Now(),})}b.Insert(bulkPosts...)if _,err:=b.Run();err!=nil{fmt.Println(err)}fmt.Println(time.Since(t))
}

2.5 更新文档

//更新文档操作
func TestUpdate(){fmt.Println("Test Update in mongo DB -->")selector := bson.M{"title":"post1"}update :=bson.M{"$set":bson.M{"title":"post1-update"}}if err := Coll.Update(selector,update);err!=nil{fmt.Println(err)}
}

2.6 添加或者更新文档(upsert)

//添加或更新文档
func TestUpsert() {fmt.Println("Test Upsert in Mongo DB -->")//添加或者更新文档update := bson.M{"$set": bson.M{"content": "post-upsert-content"}}selector := bson.M{"title": "post-upsert-title"}_, err := Coll.Upsert(selector, update)if err != nil {panic(err)}
}

2.7 查询文档

//查询文档
func TestSelect(){fmt.Println("Test Select in Mongo DB -->")var result Postsvar results []Postsif err:=Coll.Find(bson.M{"title":"post1-update"}).One(&result);err!=nil{fmt.Println(err)}fmt.Printf("find one:%v\n",result)if err:=Coll.Find(bson.M{"title":"post1-update"}).All(&results);err!=nil{fmt.Println(err)}fmt.Printf("find all:%v\n",results)if err:=Coll.Find(bson.M{"title":"post1-update"}).All(&results);err!=nil{fmt.Println(err)}if err:=Coll.Find(bson.M{"title":"post1-update"}).Limit(1).All(&results);err!=nil{fmt.Println(err)}fmt.Printf("find limit:%v\n",results)
}

2.8 聚合操作

//聚合操作
func TestAggregate(){pipeline := []bson.M{{"$match": bson.M{"title": "post1-update" }},}pipe := Coll.Pipe(pipeline)result := []bson.M{}//err := pipe.AllowDiskUse().All(&result) //allow disk useerr := pipe.All(&result)if err != nil {panic(err)}fmt.Println("find TestAggregate result:", result)
}

2.9 直接将json保存到mongoDB中

func saveJsonToDB(){var f interface{}j:=[]byte(`{"posts": {"title": "post1","content": "post1-content"}
}`)if err:=json.Unmarshal(j,&f);err!=nil{fmt.Println(err)}fmt.Printf("%v",&f)if err:=Coll.Insert(&f);err!=nil{fmt.Println(err)}}

3.完整代码

package mainimport ("encoding/json""fmt""gopkg.in/mgo.v2""gopkg.in/mgo.v2/bson""time"
)type Posts struct {Title stringContent stringDate time.Time
}var (Session,_ = mgo.Dial("localhost")Database = "mgo"Collection = "posts"Coll = Session.DB(Database).C(Collection)
)// Drop Database
func DropDatebase(){fmt.Println("drop Database -->")if err :=Session.DB(Database).DropDatabase();err!=nil{fmt.Println("drop Datebase fail!!")}
}// 添加一个文档
func TestInsert(){fmt.Println("insert document to mongo DB -->")post1 := &Posts{Title:   "post1",Content: "post1-content",Date:    time.Now(),}Coll.Insert(post1)}
// 添加多个文档
func TestMultipleInsert(){t:=time.Now()fmt.Println("insert Multi document -->")var multiPosts []interface{}for i:=1;i<5001;i++{multiPosts = append(multiPosts,&Posts{Title:   fmt.Sprintf("post-%d",i),Content: fmt.Sprintf("post-%d-content",i),Date:    time.Now(),})}Coll.Insert(multiPosts...)fmt.Println(time.Since(t))
}//批量插入
func TestBulkInsert(){t:=time.Now()fmt.Println("Bulk Insert -->")b :=Coll.Bulk()var bulkPosts []interface{}for i:=10;i<5010;i++{bulkPosts = append(bulkPosts,&Posts{Title:   fmt.Sprintf("post-%d",i),Content: fmt.Sprintf("post-%d-content",i),Date:    time.Now(),})}b.Insert(bulkPosts...)if _,err:=b.Run();err!=nil{fmt.Println(err)}fmt.Println(time.Since(t))
}//更新文档操作
func TestUpdate(){fmt.Println("Test Update in mongo DB -->")selector := bson.M{"title":"post1"}update :=bson.M{"$set":bson.M{"title":"post1-update"}}if err := Coll.Update(selector,update);err!=nil{fmt.Println(err)}
}//添加或更新文档
func TestUpsert() {fmt.Println("Test Upsert in Mongo DB -->")//添加或者更新文档update := bson.M{"$set": bson.M{"content": "post-upsert-content"}}selector := bson.M{"title": "post-upsert-title"}_, err := Coll.Upsert(selector, update)if err != nil {panic(err)}
}//查询文档
func TestSelect(){fmt.Println("Test Select in Mongo DB -->")var result Postsvar results []Postsif err:=Coll.Find(bson.M{"title":"post1-update"}).One(&result);err!=nil{fmt.Println(err)}fmt.Printf("find one:%v\n",result)if err:=Coll.Find(bson.M{"title":"post1-update"}).All(&results);err!=nil{fmt.Println(err)}fmt.Printf("find all:%v\n",results)if err:=Coll.Find(bson.M{"title":"post1-update"}).All(&results);err!=nil{fmt.Println(err)}if err:=Coll.Find(bson.M{"title":"post1-update"}).Limit(1).All(&results);err!=nil{fmt.Println(err)}fmt.Printf("find limit:%v\n",results)
}//聚合操作
func TestAggregate(){pipeline := []bson.M{{"$match": bson.M{"title": "post1-update" }},}pipe := Coll.Pipe(pipeline)result := []bson.M{}//err := pipe.AllowDiskUse().All(&result) //allow disk useerr := pipe.All(&result)if err != nil {panic(err)}fmt.Println("find TestAggregate result:", result)
}//保存json到mongo
func saveJsonToDB(){var f interface{}j:=[]byte(`{"posts": {"title": "post1","content": "post1-content"}
}`)if err:=json.Unmarshal(j,&f);err!=nil{fmt.Println(err)}fmt.Printf("%v",&f)if err:=Coll.Insert(&f);err!=nil{fmt.Println(err)}}
func main(){TestInsert()TestUpdate()TestUpsert()TestSelect()TestAggregate()TestMultipleInsert()TestBulkInsert()saveJsonToDB()defer Session.Close()
}

go中mgo操作数据库的一些示例相关推荐

  1. python中cursor的用法_python MySQLdb用法,python中cursor操作数据库(转)

    数据库连接 连接数据库前,请先确认以下事项: 您已经创建了数据库 TESTDB. 在TESTDB数据库中您已经创建了表 EMPLOYEE EMPLOYEE表字段为 FIRST_NAME, LAST_N ...

  2. jdba访问mysql_Java中JDBC操作数据库的步骤

    Java中JDBC操作数据库的步骤,今天给喜欢Java开发或者是想要参加Java培训学习的小伙伴们分享一些Java技能干货,那就是Java阐述jdba操作数据库的步骤,废话不多说了,随小编一起来看一下 ...

  3. mysql 中caption_Django-Model操作数据库(增删改查、连表结构)(示例代码)

    Django-Model操作数据库(增删改查.连表结构) 一.数据库操作 1.创建model表 基本结构 from django.db importmodelsclassuserinfo(models ...

  4. python中cursor操作数据库(转)

    原文出处:http://doudouclever.blog.163.com/blog/static/175112310201284115340663/ python 操作数据库,要安装一个Python ...

  5. TP6中db操作数据库的方式(方法)和ORM模型操作数据库的方式(方法)

    db库认知基础 注:orm独立出来了,与tp5不同 配置数据库: 通过env文件来具体配置,目的是不同的环境下,如线上服务器的配置只需要使用本环境的env文件就可以直接更改配置了 使用db: ① tp ...

  6. ado 阿里云 mysql_ADO 操作数据库(一)--Ado简介

    ADO是微软一套访问数据源的对象组件模型(COM),它是MDAC(微软数据访问组件)的一部分,MDAC结构如下图: 图.1 MDAC结构图 ADO在编程语言与OLE DB间提供了一个中间层这就允许程序 ...

  7. Python学习笔记(3):Python操作数据库

    安装MySQLdb 默认情况下Python中并没有安装MySQLdb,因此,在使用之前,我们要先安装MySQLdb. 安装步骤: 首先要下载MySQL-Python,下载地址是https://pypi ...

  8. 黄聪:使用Wordpress中的wpdb类操作数据库

    WordPress包含一个操作数据库的类--wpdb,该类基于ezSQL(由Justin Vincent维护的数据库操作项目)编写,包含了其基本的功能. 使用说明 请不要直接调用wpdb类中的方法.W ...

  9. mysql中的操作指令,MySQL中常用指令操作的介绍(代码示例)

    本篇文章给大家带来的内容是关于MySQL中常用指令操作的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. l 创建数据库:CREATE DATABASE table_n ...

最新文章

  1. 报名 | 2019年社会计算机国际会议
  2. mysql写放大,canvas实现图片根据滑块放大缩小效果
  3. Flutter介绍 - Flutter,H5,React Native之间的对比
  4. 数据产品通用复合指标查询计算的实践
  5. opencv cv2.LUT()(使用查找表中的值填充输出数组)
  6. 深入理解spark两种调度模式:FIFO,FAIR模式
  7. access 查找工龄大于30_ACCESS查询操作题完整
  8. python基础教程(十一)
  9. WebStorm文件类型关联设置
  10. 通讯软件通常要哪几个端口_您通常打开几个浏览器标签?
  11. marquee标签、插入百度地图
  12. Python3.0的新改动
  13. 在打包的时候,创建应用程序池,并自动将程序assign到新创建的池中(MSI制作)
  14. 蓝桥杯 ALGO-158 算法训练 sign函数
  15. 算法 排序 python 实现--堆排序
  16. kafka常用的操作命令
  17. 最新xmlns:android=http://schemas.android.com/apk/res/android的理解
  18. FFmpeg 内容介绍 音视频解码和播放
  19. html的长度单位的选择,html中常见长度单位有哪些?
  20. IP数据报首部的格式identification

热门文章

  1. 《PHASEN:A Phase and Harmonics-Aware Speech Enhancement Network》Pytorch代码学习Ⅱ
  2. 如何设置虚拟机访问外网
  3. 机器学习数据挖掘笔记_18(PGM练习二:贝叶斯网络在遗传图谱在的应用)
  4. 在HTML中实现两个div并排显示
  5. memcached启动脚本
  6. AppleParty(苹果派)v3 支持 App Store 新定价机制 - 批量配置自定价格和销售范围
  7. 【百度分享】BZFS—一种透明压缩文件系统
  8. AutoJs学习-MC我的世界自动钓鱼
  9. 实现人rou搜索的10个经典方法
  10. 按头安利 好看又实用的运动健身 体育海报模板素材看这里