mongodb
Install
go get -u go.mongodb.org/mongo-driver/bson
Test
package test
import (
"context"
"fmt"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
"path"
"runtime"
"testing"
)
func TestMongoDB(t *testing.T) {
client, err := mongo.Connect(context.TODO(), options.Client().SetAuth(options.Credential{
Username: "username",
Password: "password",
}).ApplyURI("uri"))
if err != nil {
t.Fatal(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
t.Fatal(err)
}
}()
// Ping the primary
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
t.Fatal(err)
}
fmt.Println("Successfully connected mongodb and pinged.")
}
func GetPath(file, dir string) string {
if dir == "" {
dir = "/config/"
}
_, filename, _, _ := runtime.Caller(0)
root := path.Dir(path.Dir(filename)) //获取当前工作目录
dirPath := path.Dir(root + dir) // 获取配置文件的目录
filePath := path.Join(dirPath, file) // 获取配置文
return filePath
}
Init
- 定义一个保存数据库的URI常量
- 自建服务器格式: ![[Pasted image 20230114031810.png]]
- Mongo的集群的服务器格式:
mongodb+csv://user:pass@sample.host:27017/
例:
const URI = "mongodb://root:msdnmm@192.168.0.152:27017/"
- 创建客户端 mongodb 语法:
mongo.Connect(context,options.Client().ApplyURI(uri)) (client, err)
参数
context: 上下文- options: 选项, 用于连接数据库的选项
- uri: 数据库的URI
const URI = "mongodb://root:msdnmm@192.168.0.152:27017/"
var Client, MongodbErr = mongo.Connect(context.TODO(), options.Client().ApplyURI(URI))
if MongodbErr != nil {
panic(MongodbErr)
}
- 连接数据库文档
语法:
mongo.Connect(context.TODO(), options.Client().ApplyURI(URI)).Database("database_name").Collection("collection_name")
参数:
Database: 数据库名
Collection: 文档名(表名)
例:
var Client, MongodbErr = mongo.Connect(context.TODO(), options.Client().ApplyURI(URI))
if MongodbErr != nil {
panic(MongodbErr)
}
coll := Client.Database("golang").Collection("users")
Use
单结果查询FindOne()
find 语法:
struct.FindOne(content, filter).Decode(&strcut) err
参数:
FindOne:
content: 上下文filter: 查询条件
Decode:
strcut结构体, 需要传递该结构体的指针, 进行修改
返回值:
- 失败信息
查询失败返回
mongo.ErrNoDocuments
使用:
- 定义结构体接收数据库返回的值, 一般与数据库的字段相对应
- 定义查询条件
- 查询
- 将返回的
bson二进制json结果转成所需格式
前提:
向数据库插入如下指令:
use golang_server
db.users.insertOne({
username:"lisa",
password:"123456"
})
例:
// Person 用户结构
type Person struct {
Username string `json:"username" bson:"username" binding:"required,min=1,max=20"` // 如果需要对数据传递参数, 必须使用bson 这个tag
Password string `json:"password" binding:"required,min=1,max=20"`
}
var Client, MongodbErr = mongo.Connect(context.TODO(), options.Client().ApplyURI(URI))
if MongodbErr != nil {
panic(MongodbErr)
}
func main() {
coll := Client.Database("golang_server").Collection("ratings") // 连接数据库
var person Person
filter := bson.D{{"username", "lisa"}} // 设置查询条件
// 返回结果, 如果成功则将返回的bson结果绑定到结构体
err := person.FindOne(content.TODO(), filter).Decode(&person)
if err != nil {
if findErr == mongo.ErrNoDocuments{
fmt.Println("要查询的数据在数据库中不存在")
}
panic(result.re)
}
res,_ := json.Marshal(person) // 将bson二进制json转为json
fmt.Println(string(res)) // 以字符串形式输出转换结果
}
多结果查询Find()
语法:
result, err := struct.Find(context, filter) (result, err)
err = result.All(context, &result) (err)