
本文详解如何使用 go 官方 mongodb 驱动(mongo-go-driver)准确查询并反序列化包含嵌套数组的 mongodb 文档,以完整获取如 `region` 这类数组字段及其全部元素。
在 Go 中操作 MongoDB 时,若需完整提取文档中某个数组字段(例如 region),关键在于: 正确建模数据结构 + 使用强类型反序列化 + 选择合适的驱动版本 。值得注意的是,原问题中示例代码使用的是已归档的 mgo 库(gopkg.in/mgo.v2),而当前官方推荐且持续维护的驱动是 MongoDB Go Driver(go.mongodb.org/mongo-driver/mongo)。以下教程基于该现代驱动实现,兼顾兼容性、安全性与可维护性。
✅ 正确建模嵌套数组结构
首先,根据你的文档结构定义 Go 结构体,并为每个字段添加 bson 标签(用于 BSON 解码)和 json 标签(用于后续 JSON 输出):
type City struct {ID ObjectID `bson:"_id" json:"-"` // _id 是 ObjectId 类型,输出时通常忽略 Name string `bson:"City" json:"City"` Region []Place `bson:"region" json:"region"` } type Place struct {RegionID string `bson:"regionid" json:"regionid"` HistPlace string `bson:"historical_place" json:"historical_place"`}
⚠️ 注意:ObjectID 来自 go.mongodb.org/mongo-driver/bson/primitive,需显式导入;json:”-” 表示该字段不参与 JSON 序列化,避免 _id 以原始 ObjectId 字符串形式暴露。
✅ 使用官方驱动查询并反序列化整个数组
以下是完整可运行示例(Go 1.18+,MongoDB Driver v1.14+):
package main import ("context" "encoding/json" "fmt" "log" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref") type City struct {ID primitive.ObjectID `bson:"_id" json:"-"` Name string `bson:"City" json:"City"` Region []Place `bson:"region" json:"region"` } type Place struct {RegionID string `bson:"regionid" json:"regionid"` HistPlace string `bson:"historical_place" json:"historical_place"`} func main() { // 建立连接(建议使用 context 控制超时)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27017")) if err != nil {log.Fatal("Failed to connect to MongoDB:", err) } defer func() { if err = client.Disconnect(ctx); err != nil {log.Fatal("Failed to disconnect:", err) } }() // 获取集合 collection := client.Database("db").Collection("myplace") // 查询所有文档(可替换为带 filter 的查询,如 bson.M{"City": "some city"})cursor, err := collection.Find(ctx, bson.M{}) if err != nil {log.Fatal("Find failed:", err) } defer cursor.Close(ctx) var cities []City if err = cursor.All(ctx, &cities); err != nil {log.Fatal("Decode failed:", err) } // 格式化 JSON 输出(符合预期结构)out, err := json.MarshalIndent(cities, ""," ") if err != nil {log.Fatal("JSON marshal failed:", err) } fmt.Println("Result:") fmt.Println(string(out)) }
✅ 关键要点说明
- 不要用 map[string]interface{} 临时解包 :虽可行,但丧失类型安全与 IDE 支持,难以维护。
- Find(nil) → Find(ctx, bson.M{}):新驱动强制要求传入 context.Context 和 bson.D / bson.M 查询条件。
- cursor.All() 替代 Find().All():更明确地表达“将游标中所有结果批量解码到切片”。
- 错误处理不可省略 :尤其是网络 I/O 和 BSON 解码错误,应逐层检查。
- primitive.ObjectID 是标准类型 :务必使用 primitive.ObjectIDHex() 解析字符串 ID,或用 primitive.NewObjectID() 生成新 ID。
✅ 输出效果(与预期一致)
运行后将输出如下格式化 JSON(已去除 _id 字段,仅保留 City 和完整 region 数组):
[{ "City": "some city", "region": [ { "regionid": "31", "historical_place": "temple"}, {"regionid": "32", "historical_place": "temple"}, {"regionid": "33", "historical_place": "temple"} ] } ]
✅ 总结:只要结构体标签与数据库字段名严格对应(注意大小写与下划线转换),Go 就能自动完成嵌套数组的深度反序列化——无需手动遍历或额外解析,简洁、高效、可靠。






























