当前位置:网站首页>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/mgo Now 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()
}
原网站

版权声明
本文为[You're like an ironclad treasure]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210551199626.html

随机推荐