伴隨着移動端的興起,Nosql數據庫以其分佈式設計和高性能等特色獲得了普遍的應該用,下面將介紹下Nosql中的mongoDB在Go語言中的應用,在開發前,有必要了解下基礎知識
在開發前,導入開發須要用到的類庫sql
import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "log" )
在示例中用到的結構有:數據庫
type Student struct { Id_ bson.ObjectId bson:"_id" Name string bson:"name" Phone string bson:"phone" Email string bson:"email" Sex string bson:"sex" }
數據庫鏈接主要用到了mgo中的Dial()函數,鏈接形式如mgo.Dial(url1,url2,url3),具體代碼以下:session
func ConnecToDB() *mgo.Collection { session, err := mgo.Dial("127.0.0.1:27017") if err != nil { panic(err) } //defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("medex").C("student") return c }
插入主要用到了函數 func (c *Collection) Insert(docs ...interface{}) error
下面是我插入的兩條記錄分佈式
func InsertToMogo() { c := ConnecToDB() stu1 := Student{ Name: "zhangsan", Phone: "13480989765", Email: "329832984@qq.com", Sex: "F", } stu2 := Student{ Name: "liss", Phone: "13980989767", Email: "12832984@qq.com", Sex: "M", } err := c.Insert(&stu1, &stu2) if err != nil { log.Fatal(err) } }
經過可視化工具能夠看到我插入的數據函數
{ "_id" : ObjectId("5a66a96306d2a40a8b884049"), "name" : "zhangsan", "phone" : "13480989765", "email" : "329832984@qq.com", "sex" : "F" } { "_id" : ObjectId("5a66a96306d2a40a8b88404a"), "name" : "liss", "phone" : "13980989767", "email" : "12832984@qq.com", "sex" : "M" }
查詢單個主要用到了func (c *Collection) Find(query interface{}) *Query函數,查詢單個和多個主要用到了One()和Many()函數,條件組合能夠查看mongDB數據庫使用。工具
func GetDataViaSex() { c := ConnecToDB() result := Student{} err := c.Find(bson.M{"sex": "M"}).One(&result) if err != nil { log.Fatal(err) } fmt.Println("student", result) students := make([]Student, 20) err = c.Find(nil).All(&students) if err != nil { log.Fatal(err) } fmt.Println(students) }
查詢全部形如:c.Find(nil).Many(&results)
另外,方法中也有個根據id來查詢的方法 func (c *Collection) FindId(id interface{}) *Query,性能
func GetDataViaId() { id := bson.ObjectIdHex("5a66a96306d2a40a8b884049") c := ConnecToDB() stu := &Student{} err := c.FindId(id).One(stu) if err != nil { log.Fatal(err) } fmt.Println(stu) }
更新經過函數url
*func (c *Collection) Update(selector interface{}, update interface{}) error *func (c *Collection) UpdateAll(selector interface{}, update interface{}) (info *ChangeInfo, err error) *func (c *Collection) UpdateId(id interface{}, update interface{}) error func UpdateDBViaId() { //id := bson.ObjectIdHex("5a66a96306d2a40a8b884049") c := ConnecToDB() err := c.Update(bson.M{"email": "12832984@qq.com"}, bson.M{"$set": bson.M{"name": "haha", "phone": "37848"}}) if err != nil { log.Fatal(err) } }
刪除對應的方法spa
func (c *Collection) Remove(selector interface{}) error] func (c *Collection) RemoveAll(selector interface{}) (info *ChangeInfo, err error) func (c *Collection) RemoveId(id interface{}) error func RemoveFromMgo() { c := ConnecToDB() _, err := c.RemoveAll(bson.M{"phone": "13480989765"}) if err != nil { log.Fatal(err) } }