package main
import (
"gopkg.in/mgo.v2"
"fmt"
"gopkg.in/mgo.v2/bson"
)
type Operater struct {
mogSession *mgo.Session
dbname string
document string
}
//集合的结构 其他中AGE NAME HEIGHT 名字的首字母必须大写,如果不无法访问到
type person struct {
AGE int
NAME string
HEIGHT int
}
//连接数据库
func (operater *Operater) connect() error {
mogsession, err := mgo.Dial("mongodb://127.0.0.1:27017")
if err != nil {
fmt.Println(err)
return err
}
operater.mogSession = mogsession
return nil
}
func (operater *Operater) insert(p *person) error {
collcetion := operater.mogSession.DB(operater.dbname).C(operater.document)
err := collcetion.Insert(p)
return err
}
func main() {
p:= person{
3134,
"周杰伦",
175,
}
operater := Operater{dbname: "mongd", document: "test"}
operater.connect()
//operater.insert(p)
err := operater.insert(&p)
if err != nil {
fmt.Println("插入出错", err)
}else{
fmt.Println("success!")
}
ps, _ := operater.query()
for key, value := range ps {
fmt.Println("---->",key,value)
}
}
//更新一行
func (operater *Operater) update() (error) {
collcetion := operater.mogSession.DB(operater.dbname).C(operater.document)
update := person{
33,
"詹姆斯",
201,
}
err := collcetion.Update(bson.M{"name": "周杰伦"}, update)
if err != nil {
fmt.Println(err)
}
return err
}
//统计集合中数据的个数
func (operater *Operater) query() ([]person,error) {
collcetion:=operater.mogSession.DB(operater.dbname).C(operater.document)
p:=new(person)
p.AGE=33
query:=collcetion.Find(nil)
ps:=[]person{}
query.All(&ps)
iter:=collcetion.Find(nil).Iter()
//单个查询
result:=new(person)
for iter.Next(&result) {
fmt.Println("一个一个输出:", result)
}
return ps,nil
}
golang增删改查mongdb
最新推荐文章于 2024-03-04 23:01:15 发布