Go 使用 MongoDB 实现分页查询
解决过程
CSDN 中搜到一个有 Bug 的代码
import( "context" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func Find(database *mongo.Database,collection string,limit,index int64) (data []map[string]interface,err error){ ctx, cannel := context.WithTimeout(context.Background(), time.Minute) defer cannel() var findoptions *options.FindOptions if limit > 0 { findoptions.SetLimit(limit) findoptions.SetSkip(limit * index) // 设置排序条件 // findOptions.SetSort(bson.M{"age": 1}) } cur, err := database.Collection(collection).Find(ctx, bson.M{}, findoptions) if err != nil { return nil, err } defer cur.Close(context.Background()) err = cur.All(context.Background(), &data) return }
第一个 bug , 函数 Find() 的返回值 data []map[string]interface
少了花括号, 应该是 data []map[string]interface{}
第二个 bug , 其中变量 findoptions
声明了但没有初始化, 正确写法是 var findoptions = new(options.FindOptions)
完成代码
// data []map[string]interface{} interface() 代表 通用类型的字典数据, 不需要写明返回数据的类型 // 函数参数依次是 mongodb 数据库对象, 文档名, 筛选条件(bson.M{}对象,见下面示例, 每页数据量, 第几页) func Find(database *mongo.Database, collection string, filter bson.M, limit, index int64) (data []map[string]interface{}, err error) { ctx, cannel := context.WithTimeout(context.Background(), time.Minute) defer cannel() var findoptions = new(options.FindOptions) if limit > 0 { findoptions.SetLimit(limit) findoptions.SetSkip(limit * index) } cur, err := database.Collection(collection).Find(ctx, filter, findoptions) if err != nil { return nil, err } defer cur.Close(context.Background()) err = cur.All(context.Background(), &data) return }
使用示例
// 连接MongoDB数据库 client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { fmt.Println("连接数据库失败:", err) return } defer client.Disconnect(context.Background()) // 获取数据库对象 db := client.Database("message") // 调用Find()函数查询数据 // 分页查询场景: 查询 sended 为 true 的数据, 将结果分为每页十条, 返回第一页(index 为 0) 的数据 // 返回格式为 []map[string]{} data, err := Find(db, "dev", bson.M{"sended": true}, 10, 0) if err != nil { fmt.Println("查询数据失败:", err) return } // 输出查询结果 fmt.Println(data) for _, v := range data { fmt.Println(v["phone"]) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」