由于本身不太了解Mongo,再加上网上搜索golang连接mongo的时候大家都是免密连接的,导致还是找了一段时间才找到的。这里记录一下给需要的人。
配置信息
type MongoDB struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password"`
Database string `yaml:"database"`
}
连接数据库并进行简单的插入/查询数据
package db
import (
"context"
"fmt"
"image_download/conf"
"log"
"time"
"github.com/qiniu/qmgo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//初始化mongodb客户端,参考: https://github.com/qiniu/qmgo
func InitMongo(config *conf.MongoDB) (*qmgo.QmgoClient, context.Context) {
cred := qmgo.Credential{
Password: config.Password,
Username: config.Username,
}
conf := qmgo.Config{
Uri: fmt.Sprintf("mongodb://%s:%s", config.Host, config.Port),
Database: config.Database,
Coll: fmt.Sprint("image", time.Now().Format("20060102")),
Auth: &cred,
}
ctx := context.Background()
cli, err := qmgo.Open(ctx, &conf)
if err != nil {
log.Fatal(err)
}
return cli, ctx
}
//查询mongo数据库数据
func QueryMongoData(cli *qmgo.QmgoClient, ctx context.Context) {
type UserInfo struct {
Name string `bson:"name"`
Age uint16 `bson:"age"`
Weight uint32 `bson:"weight"`
}
var userInfo = UserInfo{
Name: "xm",
Age: 7,
Weight: 40,
}
result, err := cli.InsertOne(ctx, userInfo)
if err != nil {
log.Fatal(err)
} else {
if id, ok := result.InsertedID.(primitive.ObjectID); ok {
if oid, err := id.MarshalText(); err != nil {
log.Fatal(err)
} else {
fmt.Println("result: ", string(oid))
}
}
}
one := UserInfo{}
err = cli.Find(ctx, bson.M{"name": userInfo.Name}).One(&one)
if err != nil {
fmt.Println("err", err)
}
fmt.Println("123", one)
}