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

Golang+MongoDB 之 CRUD(1)_第1张图片
正常启动显示信息如下:
Golang+MongoDB 之 CRUD(1)_第2张图片

(2) 打开robot 3T 链接 local mongoDB

Golang+MongoDB 之 CRUD(1)_第3张图片
Golang+MongoDB 之 CRUD(1)_第4张图片

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 常用符号表
Golang+MongoDB 之 CRUD(1)_第5张图片

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

你可能感兴趣的:(Golang,MongoDB)