mgo操作mongodb
mgo基本使用:
安装
# go get gopkg.in/mgo.v2
package main
import (
"fmt"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
Name string
Phone string
}
func main() {
//mongodb连接uri
//格式为[mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options]
session, err := mgo.Dial("mongodb://cord:123456@127.0.0.1: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)
}
}