標籤:bash 模糊 格式 host func main ODB pkg str
mgo基本使用:
http://labix.org/mgo
安裝
# go get gopkg.in/mgo.v2
package mainimport ( "fmt" "log" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson")type Person struct { Name string Phone string}func main() { //mongodb串連uri //格式為[mongodb://][user:[email protected]]host1[:port1][,host2[:port2],...][/database][?options] session, err := mgo.Dial("mongodb://cord:[email protected]:27010/keymap") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) c := session.DB("test").C("people") //增加記錄 err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, &Person{"Cla", "+55 53 8402 8510"}) if err != nil { log.Fatal(err) } result := Person{} //普通查詢 err = c.Find(bson.M{"name": "Ale"}).One(&result) //正則匹配(模糊查詢),其中"$options":"$i"表示忽略大小寫 //regexStr = "A" //err = c.Find(bson.M{"name":bson.M{"$regex" : regexStr, "$options":"$i"}}).All(&result) if err != nil { log.Fatal(err) } fmt.Println("Phone:", result.Phone) //刪除記錄 err = c.Remove(bson.M{"name":"Ale"}) //刪除單條,如果有多條,預設順序第一條 _, err = c.RemoveAll(bson.M{"name":"Ale"}) //刪除所有尋找的 if err != nil { fmt.Println(err) }}
mgo操作mongodb