mongo-goclient,插入数据使用collection.Insert()函数,插入的是结构体地址
例如:
type Student struct {
Name string
Age int
}
p := Student{"张三", 12}
err := cpllection.Insert(&p)
源码如如下:
package mongo
import (
"fmt"
"gopkg.in/mgo.v2"
"testing"
)
var url string
var username string
var password string
var database string
var collection string
var mgoDB *mgo.Database
var mgoCollect *mgo.Collection
var session *mgo.Session
type Student struct {
Name string
Age int
}
func TestManager_Register(t *testing.T) {
fmt.Printf("Opening mongo sink \n")
// 创建链接
session, err := mgo.Dial(fmt.Sprintf("%s", "192.168.111.199"))
if err != nil {
fmt.Println("mongo connect failed.")
}
// 选择DB
mgoDB = session.DB("admin")
// 登录
err = mgoDB.Login("admin", "123456")
if err != nil {
fmt.Println("mongo login failed.")
}
// 选择集
mgoCollect = mgoDB.C("test")
p := Student{"张三", 12}
err = mgoCollect.Insert(&p)
if err != nil {
fmt.Println(err)
}
fmt.Println("mongo insert success.")
}
有问题欢迎留言讨论,不定时回复!