相关库资源:https://github.com/mongodb/mongo-go-driver
//该文件主要用于初始化mongoClient供全局调用
package mongodb
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
var (
MongoDb *mongo.Client
)
func init() {
fmt.Println("start mongodb init ....")
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
defer cancel()
var err error
MongoDb, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017").SetMaxPoolSize(30).SetMaxConnIdleTime(time.Duration(30) * time.Second).SetConnectTimeout(time.Duration(3) * time.Second).SetTimeout(time.Duration(10) * time.Second))
if err != nil {
panic(any(err))
}
fmt.Println("end mongodb init ....")
}
//该文件演示了如果使用mongoClient进行相关操作
package main
import (
"context"
"fmt"
"go-test/mongodb"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"log"
)
func main() {
result := make(map[string]interface{})
collection := mongodb.MongoDb.Database("test").Collection("ceshi")
filter := bson.D{{"uid", 1024}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err == mongo.ErrNoDocuments {
// Do something when no record was found
fmt.Println("record does not exist")
return
} else if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
以上为演示代码,具体内容和示例请看官方文档介绍。