You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言REST API连接MongoDB失败求助

Go连接MongoDB报错"no reachable servers"的解决方法

问题场景

尝试通过Go语言连接MongoDB并插入电影数据,MongoDB服务在Windows中已正常运行,试过localhost和127.0.0.1作为连接地址,但运行代码时始终报错panic: no reachable servers。

操作日志

PS D:\goprojects\GO_RESTAPI_MONGDB> go mod init mgo.v2 
go: creating new go.mod: module mgo.v2
go: to add module requirements and sums:
        go mod tidy
PS D:\goprojects\GO_RESTAPI_MONGDB> go mod tidy
go: finding module for package gopkg.in/mgo.v2/bson
go: finding module for package gopkg.in/mgo.v2
go: found gopkg.in/mgo.v2 in gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
go: found gopkg.in/mgo.v2/bson in gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
go: finding module for package gopkg.in/yaml.v2
go: finding module for package gopkg.in/check.v1
go: downloading gopkg.in/yaml.v2 v2.4.0
go: downloading gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c
go: found gopkg.in/check.v1 in gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c
go: found gopkg.in/yaml.v2 in gopkg.in/yaml.v2 v2.4.0
go: downloading github.com/kr/pretty v0.2.1
go: downloading github.com/kr/text v0.1.0
PS D:\goprojects\GO_RESTAPI_MONGDB> go run main.go
Hello world
panic: no reachable servers

goroutine 1 [running]:
main.main()
        D:/goprojects/GO_RESTAPI_MONGDB/main.go:27 +0x538
exit status 2

原始代码

package main

import (
    "fmt"
    mgo "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "log"
)

type Movie struct {
    Name      string   `bson:"name"`
    Year      string   `bson:"year"`
    Directors []string `bson:"directors"`
    Writers   []string `bson:"writers"`
    BoxOffice `bson:"boxOffice"`
}

type BoxOffice struct {
    Budget uint64 `bson:"budget"`
    Gross  uint64 `bson:"gross"`
}

func main() {
    fmt.Println("Hello world")
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    c := session.DB("appDB").C("movidesData")
    darkNight := &Movie{
        Name:      "Dark Night",
        Year:      "2009",
        Directors: []string{"Chirstopher Nolan"},
        Writers:   []string{"Max Muler"},
        BoxOffice: BoxOffice{
            Budget: 150000,
            Gross:  1750000000,
        },
    }
    err = c.Insert(darkNight)
    if err != nil {
        log.Fatal(err)
    }
    result := Movie{}
    err = c.Find(bson.M{"boxOffice.budget": bson.M{"$gt": 750000}}).One(&result)
    //err = c.Find(bson.M{"boxOffice.budget": bson.M{"$gt": 150000000}}).One(&result)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Movie Name is :", result.Name)
}

解决步骤

1. 替换废弃的mgo.v2库

gopkg.in/mgo.v2是已停止维护的第三方库,MongoDB官方提供的mongodb/mongo-go-driver是当前推荐的Go语言驱动,兼容性与稳定性更优。

执行以下命令安装官方驱动:

go get go.mongodb.org/mongo-driver/mongo
go get go.mongodb.org/mongo-driver/mongo/options
go get go.mongodb.org/mongo-driver/bson

2. 修改代码使用官方驱动

替换后的功能等价代码示例:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Movie struct {
	Name      string   `bson:"name"`
	Year      string   `bson:"year"`
	Directors []string `bson:"directors"`
	Writers   []string `bson:"writers"`
	BoxOffice `bson:"boxOffice"`
}

type BoxOffice struct {
	Budget uint64 `bson:"budget"`
	Gross  uint64 `bson:"gross"`
}

func main() {
	fmt.Println("Hello world")
	// 设置连接选项,明确指定端口(默认27017)
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接到MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 验证连接有效性
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to MongoDB!")

	// 获取目标集合
	collection := client.Database("appDB").Collection("movidesData")

	// 插入电影数据
	darkNight := Movie{
		Name:      "Dark Night",
		Year:      "2009",
		Directors: []string{"Christopher Nolan"},
		Writers:   []string{"Max Muler"},
		BoxOffice: BoxOffice{
			Budget: 150000,
			Gross:  1750000000,
		},
	}

	insertResult, err := collection.InsertOne(context.TODO(), darkNight)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)

	// 查询符合条件的电影
	var result Movie
	filter := bson.D{{"boxOffice.budget", bson.D{{"$gt", 750000}}}}

	err = collection.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			fmt.Println("No documents found matching the filter")
			return
		}
		log.Fatal(err)
	}
	fmt.Println("Movie Name is :", result.Name)

	// 断开连接
	err = client.Disconnect(context.TODO())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Disconnected from MongoDB!")
}

3. 排查连接基础问题

若替换驱动后仍报错,检查以下内容:

  • 确认MongoDB服务状态:打开任务管理器→服务,确保MongoDB服务处于"正在运行"状态
  • 检查端口配置:查看MongoDB配置文件mongod.cfg,确认net.port未被修改(默认27017)
  • 防火墙拦截:临时关闭Windows防火墙测试,或添加允许Go程序访问27017端口的规则
  • MongoDB绑定IP:检查mongod.cfg中的net.bindIp,确保包含127.0.0.1或0.0.0.0(允许本地/所有IP访问)

内容的提问来源于stack exchange,提问作者shubhra garg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:24:55