const (
uri = "mongodb://127.0.0.1:27017/admin"
//poolSize 连接池大小
poolSize = 100
)
var (
// Client mongodb client
Client *mgo.Session
)
func init() {
var err error
Client, err = mgo.Dial(uri)
if err != nil {
panic("database connection failed:" + err.Error())
}
Client.SetPoolLimit(poolSize)
}
package main
import (
"fmt"
"github.com/prometheus/common/log"
)
type User struct {
Name string `bson:"name"`
Gender int `bson:"gender"`
Age int `bson:"age"`
}
const (
GeneralGender = iota
Male
Female
)
const (
DBName = "redcoast"
UserColl = "user"
)
func main() {
user := &User{
Name: "jack",
Gender: Male,
Age: 21,
}
session := Client.Copy()
err := session.DB(DBName).C(UserColl).Insert(user)
if err != nil {
log.Error(err)
} else {
fmt.Println(user)
}
}