使用Golang和Jetbrain Goland连接MongoDB Atlas的方法
使用Golang和Jetbrain Goland连接MongoDB Atlas的方法 我正在尝试连接MongoDB Atlas,但未能成功。我试图通过数据库选项卡进行连接,而不是通过Go代码连接。我是Go和MongoDB的新手。提前感谢您的帮助。
1 回复
更多关于使用Golang和Jetbrain Goland连接MongoDB Atlas的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Goland中连接MongoDB Atlas,可以通过数据库工具直接配置。以下是具体步骤:
- 打开Goland,点击右侧的"Database"工具窗口
- 点击"+“号,选择"MongoDB”
- 在连接配置中填写:
- Host:
your-cluster.mongodb.net - Port:
27017 - Authentication: 选择"SCRAM-SHA-256"
- User: 你的Atlas用户名
- Password: 你的Atlas密码
- Authentication database:
admin
- Host:
- 在"SSH/SSL"选项卡中:
- 勾选"Use SSL"
- SSL method: 选择"CA Certificate"
- CA file: 下载Atlas提供的证书或使用系统证书
如果需要通过Go代码连接,示例代码如下:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// Atlas连接字符串
uri := "mongodb+srv://username:password@cluster.mongodb.net/test?retryWrites=true&w=majority"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOptions := options.Client().ApplyURI(uri)
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// 测试连接
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("成功连接到MongoDB Atlas!")
// 断开连接
defer func() {
if err = client.Disconnect(ctx); err != nil {
log.Fatal(err)
}
}()
}
确保已安装MongoDB驱动:
go get go.mongodb.org/mongo-driver/mongo
注意替换连接字符串中的用户名、密码和集群地址为你的实际Atlas信息。

