当前位置:网站首页>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()
}
边栏推荐
- Tape SVG animation JS effect
- Hello C (VII) - structure
- After 5 years of software testing in didi and ByteDance, it's too real
- [figure database performance and scenario test sharp tool ldbc SNB] series I: introduction to data generator & Application to ges service
- svg+js键盘控制路径
- wx小程序跳转页面
- im即时通讯开发应用保活之进程防杀
- D omit parameter name
- Do280openshift access control -- encryption and configmap
- 【Proteus仿真】定时器0作为16位计数器使用示例
猜你喜欢

Ten commandments of self-learning in machine learning
Is it so difficult to calculate the REM size of the web page according to the design draft?

Hibernate学习3 - 自定义SQL

JDBC - database connection

∞符号线条动画canvasjs特效

机器学习自学成才的十条戒律

同济、阿里获CVPR最佳学生论文,李飞飞获黄煦涛奖,近6000人线下参会

VR全景怎么赚钱?结合市场从两个方面客观分析下

融合模型权限管理设计方案

Color gradient gradient color collection
随机推荐
Is it so difficult to calculate the REM size of the web page according to the design draft?
What is the difference between one way and two way ANOVA analysis, and how to use SPSS or prism for statistical analysis
【面试题】什么是事务,什么是脏读、不可重复读、幻读,以及MySQL的几种事务隔离级别的应对方法
5G dtu无线通信模块的电力应用
Hibernate学习3 - 自定义SQL
MySQL semi sync replication
Ten commandments of self-learning in machine learning
Power application of 5g DTU wireless communication module
Alternative to log4j
机器学习自学成才的十条戒律
Common redis commands in Linux system
The file containing the file operation vulnerability (6)
Phprunner 10.7.0 PHP code generator
中低速航空航天电子总线概述
无需显示屏的VNC Viewer远程连接树莓派
教程详解|在酷雷曼系统中如何编辑设置导览功能?
Transition from digitalization to intelligent manufacturing
Tape SVG animation JS effect
linux 系统redis常用命令
[leaderboard] Carla leaderboard leaderboard leaderboard operation and participation in hands-on teaching