当前位置:网站首页>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()
}
边栏推荐
- 美国众议院议员:数字美元将支持美元作为全球储备货币
- OTT营销之风正盛,商家到底该怎么投?
- How can I persuade leaders to use DDD to construct the liver project?
- wx小程序跳转页面
- [figure database performance and scenario test sharp tool ldbc SNB] series I: introduction to data generator & Application to ges service
- C程序设计专题 15-16年期末考试习题解答(上)
- Global and Chinese 3-Chlorobenzaldehyde industry operation mode and future development trend report 2022 ~ 2028
- Human body transformation vs digital Avatar
- Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
- 5年,从“点点点”到现在的测试开发,我的成功值得每一个借鉴。
猜你喜欢
wx小程序跳转页面
U.S. House of Representatives: digital dollar will support the U.S. dollar as the global reserve currency
One way 和two way ANOVA分析的区别是啥,以及如何使用SPSS或者prism进行统计分析
怎么把wps表格里某一列有重复项的整行删掉
How does VR panorama make money? Based on the objective analysis of the market from two aspects
信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)
有趣的checkbox计数器
Color gradient gradient color collection
Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)
svg线条动画背景js特效
随机推荐
JDBC - database connection
Phprunner 10.7.0 PHP code generator
Analysis report on operation mode and future development of global and Chinese methyl cyclopentanoate industry from 2022 to 2028
Hibernate learning 2 - lazy loading (delayed loading), dynamic SQL parameters, caching
Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)
Unmanned driving: Some Thoughts on multi-sensor fusion
教程详解|在酷雷曼系统中如何编辑设置导览功能?
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
Adding, deleting, modifying and checking in low build code
信号完整性(SI)电源完整性(PI)学习笔记(一)信号完整性分析概论
China CAE industry investment strategic planning and future development analysis report 2022 ~ 2028
创意SVG环形时钟js特效
Current situation analysis and development trend forecast report of global and Chinese acrylonitrile butadiene styrene industry from 2022 to 2028
Global and Chinese tetrahydrofurfuryl butyrate industry operation pattern and future prospect report 2022 ~ 2028
ArcGIS loads free online historical images as the base map (no plug-ins are required)
Common redis commands in Linux system
Investment analysis and prospect forecast report of global and Chinese octadecyl cyclopentanoate industry from 2022 to 2028
Reservoir dam safety monitoring
为什么生命科学企业都在陆续上云?
有趣的checkbox计数器