当前位置:网站首页>Some examples of MgO operating database in go
Some examples of MgO operating database in go
2022-06-25 00:16:00 【You're like an ironclad treasure】
Blog :https://hzeyuan.cn
Used to python, The database is operated by mongoengine, Now it's changed to go, I found a very good operation mongoDB drive ,mgo!
Example github Address :https://github.com/hzeyuan/learnGO/tree/master/mgo-examples
1.mgo Installation
go get gopkg.in/mgo.v2
github Address :
https://github.com/go-mgo/mgoNow maintenance has been stopped !
2. Here are some basic operations that we actually encounter
2.0
Define some basic variables before you start
- Posts The structure represents the article we want to store ,
- Seession: Connected to the mongo
- Databse: Is the name of the database we want to create
- Collection: Is the name of the collection we created
type Posts struct {
Title string
Content string
Date time.Time
}
var (
Session,_ = mgo.Dial("localhost")
Database = "mgo"
Collection = "posts"
Coll = Session.DB(Database).C(Collection)
)
2.1 Delete database
// Drop Database
func DropDatebase(){
fmt.Println("drop Database -->")
if err :=Session.DB(Database).DropDatabase();err!=nil{
fmt.Println("drop Datebase fail!!")
}
}
2.2 Add a document
// Add a document
func TestInsert(){
fmt.Println("insert document to mongo DB -->")
post1 := &Posts{
Title: "post1",
Content: "post1-content",
Date: time.Now(),
}
Coll.Insert(post1)
}
2.3 Add multiple documents
// Add multiple documents
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 Batch insert multiple documents
// Batch insert
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 Update the document
// Update document action
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 Add or update documents (upsert)
// Add or update documents
func TestUpsert() {
fmt.Println("Test Upsert in Mongo DB -->")
// Add or update documents
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 Query the document
// Query the document
func TestSelect(){
fmt.Println("Test Select in Mongo DB -->")
var result Posts
var results []Posts
if 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 Aggregation operation
// Aggregation operation
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 use
err := pipe.All(&result)
if err != nil {
panic(err)
}
fmt.Println("find TestAggregate result:", result)
}
2.9 Direct will json Save to mongoDB in
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. Complete code
package main
import (
"encoding/json"
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
)
type Posts struct {
Title string
Content string
Date 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!!")
}
}
// Add a document
func TestInsert(){
fmt.Println("insert document to mongo DB -->")
post1 := &Posts{
Title: "post1",
Content: "post1-content",
Date: time.Now(),
}
Coll.Insert(post1)
}
// Add multiple documents
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))
}
// Batch insert
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))
}
// Update document action
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)
}
}
// Add or update documents
func TestUpsert() {
fmt.Println("Test Upsert in Mongo DB -->")
// Add or update documents
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)
}
}
// Query the document
func TestSelect(){
fmt.Println("Test Select in Mongo DB -->")
var result Posts
var results []Posts
if 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)
}
// Aggregation operation
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 use
err := pipe.All(&result)
if err != nil {
panic(err)
}
fmt.Println("find TestAggregate result:", result)
}
// preservation json To 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()
}
边栏推荐
- 信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)
- Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
- Dry and wet contacts
- The new employee of the Department after 00 is really a champion. He has worked for less than two years. The starting salary of 18K is close to me when he changes to our company
- Current situation analysis and development trend prediction report of hesperidase industry in the world and China from 2022 to 2028
- Ott marketing is booming. How should businesses invest?
- Wx applet jump page
- linux 系统redis常用命令
- MySQL semi sync replication
- What are the advantages of VR panoramic production? Why is it favored?
猜你喜欢

How to delete the entire row with duplicate items in a column of WPS table

DO280OpenShift访问控制--加密和ConfigMap

Fast pace? high pressure? VR panoramic Inn brings you a comfortable life

Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it

Ott marketing is booming. How should businesses invest?
Fuxin Kunpeng joins in, and dragon lizard community welcomes a new partner in format document technical service

JPA学习2 - 核心注解、注解进行增删改查、List查询结果返回类型、一对多、多对一、多对多

创意SVG环形时钟js特效
Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it

Related operations of ansible and Playbook
随机推荐
MySQL semi sync replication
走近Harvest Moon:Moonbeam DeFi狂欢会
How to delete the entire row with duplicate items in a column of WPS table
im即时通讯开发应用保活之进程防杀
Modstart: embrace new technologies and take the lead in supporting laravel 9.0
【面试题】什么是事务,什么是脏读、不可重复读、幻读,以及MySQL的几种事务隔离级别的应对方法
Tape SVG animation JS effect
Adding, deleting, modifying and checking in low build code
Analysis report on operation mode and future development of global and Chinese methyl cyclopentanoate industry from 2022 to 2028
Investment analysis and prospect forecast report of global and Chinese octadecyl cyclopentanoate industry from 2022 to 2028
Unmanned driving: Some Thoughts on multi-sensor fusion
One way 和two way ANOVA分析的区别是啥,以及如何使用SPSS或者prism进行统计分析
Canvas spiral style animation JS special effect
Collective例子
UE4 WebBrowser图表不能显示问题
浅析大型IM即时通讯系统开发难度
有趣的checkbox计数器
Requests Library
Report on operation pattern and future prospect of global and Chinese propyl isovalerate industry from 2022 to 2028
Why do more and more physical stores use VR panorama? What are the advantages?