Go链接mongodb数据库
参考链接:
https://docs.mongodb.com/drivers/go/
https://www.mongodb.com/blog/search/golang%20quickstart
以下为部分代码:
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options"
)
func main() {
// uri:= "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
uri := "mongodb+srv://localhost:27017/monitor"
ctx, cancle := context.WithTimeout(context.Background(), 10*time.Second)
defer cancle()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
if err := client.Ping(ctx, readpref.Primary()); err != nil {
panic(err)
}
fmt.Println("Successfully connected and pinged.")
}
作者: 咕咚!
出处: https://www.cnblogs.com/linga/
关于作者:专注虚拟化,运维开发,RPA,Rust,Go,Python!
本文版权归作者和博客园共有,禁止*.csdn.net转载,禁止以盈利为目的的转载,转载文章,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(oldsixa@163.com)咨询.