Golang+MongoDB 之 CRUD(1)

Golang+MongoDB 之 CRUD(1)

初學Golang 語言與mongoDB進行交互,實現後臺API服務功能——學習golang進行簡單的增刪查改語句

"gopkg.in/mgo.v2/bson"

1、準備

(1)mongoDB 安裝

mongoDB官網下載
Robot 3T官網下載

端口號:27017
mongoDB 的鏈接字:http://127.0.0.1:27017

2、使用robot 3T 鏈接MongoDB

(1)打開 cmd 開啓mongoDB

在這裏插入圖片描述
正常啓動顯示信息如下:
在這裏插入圖片描述

(2) 打開robot 3T 鏈接 local mongoDB

在這裏插入圖片描述
在這裏插入圖片描述

3、數據結構

(1)mongodb 內部的數據結構

{
    "_id" : ObjectId("5ec744b33d8a59080fb61a7b"),
    "authLevel" : "1",
    "humanName" : "test001",
    "humanGroup" : "manager",
    "passwd" : "000000",
    "info" : "this is a manager account that is the first one ",
    "customContext" : [
        {
            "paramName" : "username",
            "paramType" : "string",
            "paramValue" : "zhangsan",
            "showOrNot" : 1
        },
        {
            "paramName" : "phone",
            "paramType" : "string",
            "paramValue" : "17192180553",
            "showOrNot" : 1
        }
    ],
    "deadOrAlive" : 2,
    "birthTime" : NumberLong(1590118476)
}

(2)golang內部的數據結構

type AuthUserInfo struct {
	AuthLevel     string          `bson:"authLevel" json:"authLevel"`
	HumanName     string          `bson:"humanName" json:"humanName"`
	HumanGroup    string          `bson:"humanGroup" json:"humanGroup"`
	Passwd        string          `bson:"passwd" json:"passwd"`
	Info          string          `bson:"info" json:"info"`
	CustomContext []CustomContext `bson:"customContext" json:"customContext"`
	DeadOrAlive   int             `bson:"deadOrAlive" json:"deadOrAlive"`
	BirthTime     int64           `bson:"birthTime" json:"birthTime"`
}

type CustomContext struct {
	ParamName  string `bson:"paramName" json:"paramName"`
	ParamType  string `bson:"paramType" json:"paramType"`
	ParamValue string `bson:"paramValue" json:"paramValue"`
	ShowOrNot  int    `bson:"showOrNot" json:"showOrNot"`
}

4、CRUD 語句

(1)insert

golang 內部創建 entity 對象

C1:= {
"ParamName":"username",
"ParamType":"string",
"ParamValue":"zhangsan",
"ShowOrNot":1
}
C2:= {
"ParamName":"phone",
"ParamType":"string",
"ParamValue":"17192180553",
"ShowOrNot":1
}

var customCon []CustomContext
customCon={C1,C2}

userinfo:=AuthUserInfo{
	AuthLevel:“1“,
	HumanName:“test001“,
	HumanGroup:“manager“,
	Passwd:“123456“,
	Info:“this is a account typed manager“,
	CustomContext:customCon,
	DeadOrAlive:1
	BirthTime:time.Now().Unix(), //the signal `,` is must not be delete
}

//調用方法
//func (c *Collection) Insert(docs ...interface{}) error {}

golang 內部使用如下

err := collection.Insert( userinfo )
if err != nil{
   fmt.Println(err)
}

(2)update

調用方法: func (c *Collection) Update(selector interface{}, update interface{}) error {}

selector := bson.M{"humanName": user.HumanName}
err := collection.Update(selector, userinfo)
//----or---
c.Update(
	selector,
	bson.M{"$set": bson.M{ info need to be set}}
)

調用方法:func (c *Collection) UpdateId(id interface{}, update interface{}) error {}

	id := bson.ObjectIdHex("5ec744b33d8a59080fb61a7b")
	data := bson.M{"$set": bson.M{"humanGroup": "teacher"}}
	err := collection.UpdateId(id, data)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("updateId is successful")
	}

調用方法:func (c *Collection) UpdateAll(selector interface{}, update interface{}) (info *ChangeInfo, err error) {}

	selector := bson.M{"humanGroup": "manager"}
	setStr := bson.M{"$set": bson.M{"humanGroup": "custom"}}
	info, err := collection.UpdateAll(selector, setStr)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(info)
	}

調用方法:func (c *Collection) Upsert(selector interface{}, update interface{}) (info *ChangeInfo, err error) {}

selector := bson.M{"humanName": user.HumanName}
info, err := collection.Upsert(selector, user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(info)
	}
//-------or -----------------
c.Update(
	selector,
	bson.M{"$inc": bson.M{ "country": , "china",}}
)

調用方法:func (c *Collection) UpsertId(id interface{}, update interface{}) (info *ChangeInfo, err error) {}

	newid := bson.ObjectIdHex("5ec748e53d8a59080fb61c11")
	sertStr := bson.M{"$set": bson.M{"country": "china"}}
	info, err := collection.UpsertId(newid, sertStr)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(info)
	}

	update的其他使用方式
	(1)給列表添加item
	c.Update(
		bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
		bson.M{"$push": bson.M{ "interests": "Golang", }}
	)
	(2)移除列表項
	c.Update(
		bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
		bson.M{"$pull": bson.M{ "interests": "Golang", }}
	)

(3)delete

id := bson.ObjectIdHex("5ec744b33d8a59080fb61a7b")
err := collection.RemoveId(id)

(4)query

調用方法:func (c *Collection) Find(query interface{}) *Query {}

	selector := bson.M{"humanGroup": "teacher"}
	var users AuthUserInfo
	collection.Find(selector).All(&users)

調用方法:func (c *Collection) FindId(id interface{}) *Query {}

	id := bson.ObjectIdHex("5ec748e53d8a59080fb61c11")
	var users AuthUserInfo
	collection.FindId(id).All(&users) 

!!!!注:find().One(&users)---- 如果找不到數據則會報錯

query 常用符號表
在這裏插入圖片描述

本文參考了以下兩篇博客
https://www.jianshu.com/p/b63e5cfa4ce5
https://www.cnblogs.com/williamjie/p/9692660.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章