首页 > 数据库 >Go 使用 MongoDB 实现分页查询

Go 使用 MongoDB 实现分页查询

时间:2023-04-25 10:36:53浏览次数:31  
标签:分页 err MongoDB findoptions limit context Background Go data

解决过程

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)
	}
	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"])
}

标签:分页,err,MongoDB,findoptions,limit,context,Background,Go,data
From: https://www.cnblogs.com/livebz/p/17351858.html

相关文章

  • AntDesign中a-pagination实现一次性获取所有数据下手动分页
    业务效果核心代码<template><a-paginationv-model:current="current":total="total":pageSize="pageSize"show-less-itemsshow-size-change......
  • uniapp 打包aab上传到google play的时候google 登录报异常
    因为App上传到GooglePlay后,会被重新签名(PlayAppSigning)谷歌为你生成的签名SHA-1将谷歌为你生成的签名SHA-1证书指纹复制到本应用已创建的凭据SHA-1处,点击保存后,ClientID并没有变,所以不用重新打包。现在,不用等,你可以试试Google+登录了。Google+登录ok。参考地址:https......
  • 【代理设计模式详解】C/Java/JS/Go/Python/TS不同语言实现
    简介代理模式(ProxyPattern)是一种结构型设计模式,用一个类来代理另一个类或几个类的功能。在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口。延迟初始化(虚拟代理)。如果你有一个偶尔使用的重量级服务对象,一直保持该对象运行会消耗系统资源时,可使用代理模式。访问......
  • COMP3310 Indexing a Gopher.
    COMP3310-Assignment2:IndexingaGopher.Background:Thisassignmentisworth15%ofthefinalmark.Itisdueby23:55Wednesday26AprilAESTLatesubmissionswillnotbeaccepted,exceptinspecialcircumstances.oExtensionsmustberequestedasea......
  • Go中的有限状态机FSM的详细介绍
    1、FSM简介1.1有限状态机的定义有限状态机(FiniteStateMachine,FSM)是一种数学模型,用于描述系统在不同状态下的行为和转移条件。状态机有三个组成部分:状态(State)、事件(Event)、动作(Action),事件(转移条件)触发状态的转移和动作的执行。动作的执行不是必须的,可以只转移状态,不指定任何......
  • mongodb使用自带命令工具导出导入数据
    记录mongo数据库用原生自带的命令工具使用json文件方式进行导入、导出的操作!在一次数据更新中,同事把老数据进行了清空操作,但是新的逻辑数据由于某种原因(好像是她的电脑中病毒了),一直无法正常连接数据库进行数据插入,然后下午2点左右要给甲方演示,所以要紧急恢复本地的部分数据......
  • 在mac上使用docker部署Mongo数据库
    拉取镜像打开网址https://hub.docker.com/,搜索mongo,https://hub.docker.com/_/mongo执行命令dockerpullmongo启动容器执行命令dockerimage,查看到mongo的tag是5.0.16启动命令dockerrun-dit--namemongo5-p27017:27017-v/Users/huidongma/data/mongodb:......
  • drf-认证、权限、频率、过滤、排序、分页
    1.认证组件1.1局部认证1.首先写两个接口,一个查询单个一个查询所有,我们利用视图扩展类和视图子类写在一个视图类上:views.py:fromrest_framework.viewsetsimportViewSetMixinfromrest_framework.genericsimportListAPIViewfromrest_framework.mixinsimportRetrieve......
  • 1 Go语言介绍、 2 Go开发环境搭建 、3 第一个helloworld 、4 变量命名规范 、5 变量的
    目录1Go语言介绍2Go开发环境搭建3第一个helloworld4变量命名规范5变量的定义和使用1Go语言介绍#Go语言介绍Go即Golang,是Google公司2009年11月正式对外公开的一门编程语言Go是【静态强类型】语言,是区别于解析型语言的编译型语言(静态:类型固定强类型:不同类型不允许直接......
  • Go
    今日内容1Go语言介绍#Go语言介绍Go即Golang,是Google公司2009年11月正式对外公开的一门编程语言Go是【静态强类型】语言,是区别于解析型语言的编译型语言(静态:类型固定强类型:不同类型不允许直接运算)解析型语言——源代由解析器对代码进行解释执行编译型语言——源代码编......