
Go MongoDB 实战go-mongo-driver 落地大型项目全攻略MongoDB 是 Go 后端常用 NoSQL。本文从连接池、调优到 transaction 实战再到企业生产规范一次打包。一、driver 安装go get go.mongodb.org/mongo-driver/mongo连接client,err:mongo.Connect(ctx,options.Client().ApplyURI(mongodb://localhost:27017))deferclient.Disconnect(ctx)二、CRUD 基本模板col:client.Database(shop).Collection(users)// Insertres,err:col.InsertOne(ctx,bson.M{name:tom,age:30})// Findvaruser User errcol.FindOne(ctx,bson.M{_id:id}).Decode(user)// Updatefilter:bson.M{_id:id}update:bson.M{$set:bson.M{age:31}}_,errcol.UpdateOne(ctx,filter,update)// Delete_,errcol.DeleteOne(ctx,bson.M{name:tom})三、Bson vs 结构体推荐用 tagged 结构typeUserstruct{ID primitive.ObjectIDbson:_id,omitemptyNamestringbson:nameAgeintbson:age}primitive.ObjectID与 MongoDB ObjectId 互转。四、索引优化importgo.mongodb.org/mongo-driver/bson_,errcol.Indexes().CreateOne(ctx,mongo.IndexModel{Keys:bson.D{{name,1}},// 升序Options:options.Index().SetUnique(true),})生产原则主键默认存在查询热点字段建索引用col.Indexes().CreateMany批量建五、聚合管道pipeline:mongo.Pipeline{{{$match,bson.D{{status,active}}}},{{$group,bson.D{{_id,$role},{count,bson.D{{$sum,1}}},}}},}cursor,err:col.Aggregate(ctx,pipeline)聚合管道 数据库端复杂逻辑CPU 节省大。六、事务4.x 集群支持session,err:client.StartSession()defersession.EndSession(ctx)_,errsession.WithTransaction(ctx,func(sc mongo.SessionContext)(interface{},error){_,err:colA.InsertOne(sc,docA)iferr!nil{returnnil,err}_,errcolB.UpdateOne(sc,bson.M{_id:id},bson.M{$inc:bson.M{counter:1}})returnnil,err})事务要求集群是副本集/分片集群单机不能用。七、踩坑清单Cursor 必须 Close防止文件描述符耗尽Bson tag 大小写敏感保持一致Update 不存在 → 报错用 Upserttimeout 用 ctxservice 退出时能快速断driver 单例重复 Connect 会浪费 fd八、调优参数options.Client().SetMaxPoolSize(100).SetMinPoolSize(10).SetServerSelectionTimeout(500*time.Millisecond).SetSocketTimeout(2*time.Second)配置合适的连接池是高并发场景关键。九、生产实战审计日志模块funcAudit(ctx context.Context,col*mongo.Collection,opstring,userstring,doc any){_,err:col.InsertOne(ctx,bson.M{op:op,user:user,doc:doc,ts:time.Now(),trace:trace.FromContext(ctx),})iferr!nil{slog.Error(audit,err,err)}}写入单独的审计库配合 opentracing可做到审计 trace 二合一。十、总结与展望go-mongo-driver 是企业级 Go 项目首选 MongoDB 客户端。掌握索引、聚合、事务三件套能应对从简单 CRUD 到亿级数据的多种场景。未来driver 2.x 计划简化 API、提升 stream-friendly、减少反射开销。十一、参考文献MongoDB 官方文档go-mongo-driver 仓库MongoDB 索引原理解析