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")